Created
October 30, 2020 17:54
-
-
Save pbsds/1aadef15343be0ac71924e1053d4a660 to your computer and use it in GitHub Desktop.
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
# this is untested | |
from functools import wraps | |
from itertools import chain | |
def autoassign(init_method): # decorator | |
""" | |
@autoassign | |
def __init__(self, a: int, b: float): | |
pass | |
becomes: | |
def __init__(self, a: int, b: float): | |
self.a = a | |
self.b = b | |
pass | |
""" | |
args, varargs, varkw, defaults, \ | |
kwonlyargs, kwonlydefaults, annotations \ | |
= inspect.getfullargspec(init_method) | |
assert varargs is None | |
assert varkw is None | |
@wraps(init_method) | |
def wrapper(self, *args, **kwargs): | |
for name, value in zip(args[1:], chain(args, kwonlyargs)): | |
setattr(self, name, value) | |
for name, value in kwargs.items(): | |
setattr(self, name, value) | |
return init_method(self, *args) | |
return new_init_method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment