Instead of writing code like this every time I define a class:
class Foo(object):
def __init__(self, a, b, c, d, e, f, g):
self.a = a
s
If you have a lot of variables, you could pass one single configuration dict or object.
Similar to the above, though not the same... the following is very short, deals with args
and kwargs
:
def autoassign(lcls):
for key in lcls.keys():
if key!="self":
lcls["self"].__dict__[key]=lcls[key]
Use like this:
class Test(object):
def __init__(self, a, b, *args, **kwargs):
autoassign(locals())
In this package you can now find
@autoargs
inspired by answer-3653049@autoprops
to transform the fields generated by @autoargs
into @property, for use in combination with a validation library such as enforce or pycontracts. Note that this has been validated for python 3.5+
From Python 3.7+ you can use a Data Class, which achieves what you want and more.
It allows you to define fields for your class, which are attributes automatically assigned.
It would look something like that:
@dataclass
class Foo:
a: str
b: int
c: str
...
The __init__
method will be automatically created in your class, and it will assign the arguments of instance creation to those attributes (and validate the arguments).
Note that here type hinting is required, that is why I have used int
and str
in the example. If you don't know the type of your field, you can use Any from the typing module.