Setting Class Attributes in Python

Setting class attributes in python can be tedious. In this post, I want to summarize a trick that I’ve been using to simplify this process.

Class Attributes in init

In many cases, we have to save the passed init arguments to self. However, when we pass a lot of arguments, it could be tedious or prone to errors when you manually set class attributes.

class Foo:
  def __init__(self, foo1, foo2):
    self.foo1 = foo1
    self.foo2 = foo2

Instead, we could use a couple tricks to update the class attributes.

setattr and __dict__.update

A python object saves its attributes in the class dictionary. We can simply update the attributes using the class dictionary.

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

Similarly, we can use setattr to update the attributes.

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

locals() or vars()

However, the previous method prevents you from defining your input arguments. This could be a problem when you have to specify the variables for your input. For instance, I use gin-config to configure hyper-parameters and **kwargs can’t be configured. In this case, you can use the locals() or vars() commands. These will return local variables in the current scope allowing you to get access to variables in a dictionary format. You can simply pass the output to the __dict__.update to set the attributes.

class Bar:
  def __init__(self, foo1, foo2, foo3=3):
      self.__dict__.update(locals())

Leave a Comment