Search code examples
pythonclassobjectattributes

How can I create an object and add attributes to it?


I want to create a dynamic object in Python and then add attributes to it. This didn't work:

obj = object()
obj.somefield = "somevalue"

AttributeError: 'object' object has no attribute 'somefield'


For details on why it doesn't work, see Can't set attributes on instance of "object" class.


Solution

  • You could use my ancient Bunch recipe, but if you don't want to make a "bunch class", a very simple one already exists in Python -- all functions can have arbitrary attributes (including lambda functions). So, the following works:

    obj = lambda: None
    obj.somefield = 'somevalue'
    

    Whether the loss of clarity compared to the venerable Bunch recipe is OK, is a style decision I will of course leave up to you.