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
  • 119,623
  • 25
  • 170
  • 301
Philipp der Rautenberg
  • 2,212
  • 3
  • 25
  • 39

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
  • 107,652
  • 25
  • 181
  • 264
gak
  • 32,061
  • 28
  • 119
  • 154
  • 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