49

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
martineau
  • 112,593
  • 23
  • 157
  • 280
Philipp der Rautenberg
  • 2,152
  • 3
  • 23
  • 38

1 Answers1

79

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
Mad Physicist
  • 95,415
  • 23
  • 151
  • 231
gak
  • 30,970
  • 26
  • 115
  • 152
  • 2
    This seems to work for me from inside the object: self.__dict__.update(result) where result is a dict – radtek Mar 15 '16 at 05:23
  • According to [this](https://stackoverflow.com/a/56450631/1626431) answer "a mappingproxy is simply a dict with no __setattr__ method." – iedmrc Sep 04 '20 at 17:53