Created
April 18, 2017 13:48
-
-
Save judy2k/b5952c36b36b877adcb0495163678675 to your computer and use it in GitHub Desktop.
Save constructor arguments on self without writing self.x = x etc...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from inspect import signature | |
def auto_args(f): | |
sig = signature(f) # Get a signature object for the target: | |
def replacement(self, *args, **kwargs): | |
# Parse the provided arguments using the target's signature: | |
bound_args = sig.bind(self, *args, **kwargs) | |
# Save away the arguments on `self`: | |
for k, v in bound_args.arguments.items(): | |
if k != 'self': | |
setattr(self, k, v) | |
# Call the actual constructor for anything else: | |
f(self, *args, **kwargs) | |
return replacement | |
class MyClass: | |
@auto_args | |
def __init__(self, a, b, c=None): | |
pass | |
m = MyClass('A', 'B', 'C') | |
print(m.__dict__) | |
# {'a': 'A', 'b': 'B', 'c': 'C'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice, Thanks for sharing !
I actually added a
bound_args.apply_defaults()
to bind default parameters (see forked version)