How to create a new unknown or dynamic/expando object in Python

Jimmy Kane picture Jimmy Kane · Dec 24, 2012 · Viewed 31.1k times · Source

In python how can we create a new object without having a predefined Class and later dynamically add properties to it ?

example:

dynamic_object = Dynamic()
dynamic_object.dynamic_property_a = "abc"
dynamic_object.dynamic_property_b = "abcdefg"

What is the best way to do it?

EDIT Because many people advised in comments that I might not need this.

The thing is that I have a function that serializes an object's properties. For that reason, I don't want to create an object of the expected class due to some constructor restrictions, but instead create a similar one, let's say like a mock, add any "custom" properties I need, then feed it back to the function.

Answer

Ned Batchelder picture Ned Batchelder · Dec 24, 2012

Just define your own class to do it:

class Expando(object):
    pass

ex = Expando()
ex.foo = 17
ex.bar = "Hello"