-
-
Save marcocamma/2fffa983a0a541a6a39b805bf99aee9a to your computer and use it in GitHub Desktop.
Save constructor arguments on self without writing self.x = x etc...
This file contains 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) | |
# 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