How to assign a new class attribute via __dict__?

Question:

I want to assign a class attribute via a string object – but how?

Example:

class test(object):
  pass

a = test()
test.value = 5
a.value
# -> 5
test.__dict__['value']
# -> 5

# BUT:
attr_name = 'next_value'

test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item assignment

Answers:

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
Answered By: gak
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.