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

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 = someobject
obj.a = lambda: None
setattr(obj.a, '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.

Leave a Comment