Is there a shortcut for `self.somevariable = somevariable` in a Python class constructor?

class, constructor, python

Solution

One problem with

self.__dict__.update(locals())

is that it includes `self`, so you get `self.self`. It would be better to filter `self` out of `locals()`

eg.

vars(self).update((k,v) for k,v in vars().items() if k != 'self')

You can defend against accidentally overwriting methods with this variation

vars(self).update((k,v) for k,v in vars().items()
                   if k != 'self' and k not in vars(self))

If you don't want it to fail silently, you could also check beforehand like this

if any(k in vars(self) for k in vars()):
    raise blahblah
vars(self).update((k,v) for k,v in vars().items() if k != 'self')

Problem

Constructors in Python often look like this: ``` class SomeClass: def __init__(self, a, b = None, c = defC): self.a = a self.b = b or [] self.c = c ``` Is there a shortcut for this, e.g. to simply define `__init__(self,**kwargs)` and use the keys as properties of `self`?

Original source

Related problems