Skip to content Skip to sidebar Skip to footer

Dictionary-like Object In Python That Allows Setting Arbitrary Attributes

What I want to do in my code: myobj = () myobj.randomattr = 1 print myobj.randomattr ... I can implement a custom SomeClass that implements __setattr__ __g

Solution 1:

You can just use an empty class:

class A(object): pass

a = A()
a.randomattr = 1

Solution 2:

I like using the Bunch idiom for this. There are list of variations and some discussion here.


Solution 3:

One solution is to use mock's:

from mock import Mock
myobj = Mock()
myobj.randomattr = 1
print myobj.randomattr

Second solution is to use namedtuple:

from collections import namedtuple
myobj = namedtuple('MyObject', '')
myobj.randomattr = 1
print myobj.randomattr

Post a Comment for "Dictionary-like Object In Python That Allows Setting Arbitrary Attributes"