Evgenyt
Evgenyt

Reputation: 10741

Dictionary-like object in Python that allows setting arbitrary attributes

What I want to do in my code:

myobj = <SomeBuiltinClass>()
myobj.randomattr = 1
print myobj.randomattr
...

I can implement a custom SomeClass that implements __setattr__ __getattr__. But I wonder if there is already a built-in Python class or simple way to do this?

Upvotes: 4

Views: 832

Answers (3)

sirex
sirex

Reputation: 4911

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

Upvotes: 0

robince
robince

Reputation: 10967

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

Upvotes: 2

mthurlin
mthurlin

Reputation: 27315

You can just use an empty class:

class A(object): pass

a = A()
a.randomattr = 1

Upvotes: 8

Related Questions