Created
February 20, 2022 07:28
-
-
Save jarnaldich/3cf0897aa14b18a200d5d6a8100d116c to your computer and use it in GitHub Desktop.
[Automatically set attributes from __init__ args in Pyhon] #python #args #init #constructor
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
# Also check data classes and collections for this | |
import inspect | |
import functools | |
def autoargs(*include,**kwargs): | |
def _autoargs(func): | |
attrs,varargs,varkw,defaults=inspect.getargspec(func) | |
def sieve(attr): | |
if kwargs and attr in kwargs['exclude']: return False | |
if not include or attr in include: return True | |
else: return False | |
@functools.wraps(func) | |
def wrapper(self,*args,**kwargs): | |
# handle default values | |
for attr,val in zip(reversed(attrs),reversed(defaults)): | |
if sieve(attr): setattr(self, attr, val) | |
# handle positional arguments | |
positional_attrs=attrs[1:] | |
for attr,val in zip(positional_attrs,args): | |
if sieve(attr): setattr(self, attr, val) | |
# handle varargs | |
if varargs: | |
remaining_args=args[len(positional_attrs):] | |
if sieve(varargs): setattr(self, varargs, remaining_args) | |
# handle varkw | |
if kwargs: | |
for attr,val in kwargs.iteritems(): | |
if sieve(attr): setattr(self,attr,val) | |
return func(self,*args,**kwargs) | |
return wrapper | |
return _autoargs | |
# Example: | |
class Foo(object): | |
@autoargs() | |
def __init__(self,x,path,debug=False,*args,**kw): | |
pass | |
foo=Foo('bar','/tmp',True, 100, 101,verbose=True) | |
print(foo.x) | |
# bar | |
print(foo.path) | |
# /tmp | |
print(foo.debug) | |
# True | |
print(foo.args) | |
# (100, 101) | |
print(foo.verbose) | |
# True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment