How to assign a new class attribute via __dict__?

There is a builtin function for this:

setattr(test, attr_name, 10)

Reference: http://docs.python.org/library/functions.html#setattr

Example:

>>> class a(object): pass
>>> a.__dict__['wut'] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dictproxy' object does not support item assignment
>>> setattr(a, 'wut', 7)
>>> a.wut
7

Leave a Comment