Skip to content

Instantly share code, notes, and snippets.

@marcocamma
Forked from judy2k/auto_args.py
Last active April 30, 2017 00:14
Show Gist options
  • Save marcocamma/2fffa983a0a541a6a39b805bf99aee9a to your computer and use it in GitHub Desktop.
Save marcocamma/2fffa983a0a541a6a39b805bf99aee9a to your computer and use it in GitHub Desktop.
Save constructor arguments on self without writing self.x = x etc...
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)
# add defaults otherwise defaults are unbonund, thus not in the list
bound_args.apply_defaults();
# 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'}
m = MyClass('A', 'B')
print(m.__dict__)
{'b': 'B', 'a': 'A', 'c': None}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment