How can you set class attributes from variable arguments (kwargs) in python

You can use the setattr() method:

class Foo:
  def setAllWithKwArgs(self, **kwargs):
    for key, value in kwargs.items():
      setattr(self, key, value)

There is an analogous getattr() method for retrieving attributes.


You could update the __dict__ attribute (which represents the instance attributes in the form of a dictionary) with the keyword arguments:

class Bar(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

then you can:

>>> bar = Bar(a=1, b=2)
>>> bar.a
1

and with something like:

allowed_keys = {'a', 'b', 'c'}
self.__dict__.update((k, v) for k, v in kwargs.items() if k in allowed_keys)

you could filter the keys beforehand (use iteritems instead of items if you’re still using Python 2.x).

Tags:

Python