Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 424
Evgenyt Avatar asked Dec 30 '22 00:12

Evgenyt


2 Answers

You can just use an empty class:

class A(object): pass

a = A()
a.randomattr = 1
like image 64
mthurlin Avatar answered May 09 '23 11:05

mthurlin


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

like image 28
robince Avatar answered May 09 '23 09:05

robince