Can you add attributes to an object dynamically?

python, python-3.x

Solution

If you are using Python 3.3+, use types.SimpleNamespace:

>>> import types
>>> a = types.SimpleNamespace()
>>> a.attr1 = 123
>>> a.attr2 = '123'
>>> a.attr3 = [1,2,3]
>>> a.attr1
123
>>> a.attr2
'123'
>>> a.attr3
[1, 2, 3]

Problem

I would like to create an object then add attributes to the object on the fly. Here's some pseudocode EX1: ``` a = object() a.attr1 = 123 a.attr2 = '123' a.attr3 = [1,2,3] ``` EX2: the first page of this PDF In Python is it possible to add attributes to an object on the fly (similar to the two examples I gave)? If yes, how?

Original source