A dictionary-like object in Python that allows you to set 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'm wondering if there is an already built-in Python class or an easy way to do this?

+4
source share
3 answers

You can simply use an empty class:

 class A(object): pass a = A() a.randomattr = 1 
+8
source

I like to use this idiom Bunch. There is a list of options and some discussions here .

+2
source

One solution is to use mock's:

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

The second solution is to use namedtuple:

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

Source: https://habr.com/ru/post/1302659/


All Articles