Skip to content

Instantly share code, notes, and snippets.

@judy2k
Created April 18, 2017 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save judy2k/b5952c36b36b877adcb0495163678675 to your computer and use it in GitHub Desktop.
Save judy2k/b5952c36b36b877adcb0495163678675 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)
# 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'}
@marcocamma
Copy link

Very nice, Thanks for sharing !
I actually added a bound_args.apply_defaults() to bind default parameters (see forked version)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment