[Tutor] question about metaclasses

Steven D'Aprano steve at pearwood.info
Wed Jan 10 12:54:38 EST 2018


On Wed, Jan 10, 2018 at 04:08:04PM +0000, Albert-Jan Roskam wrote:

> In another thread on this list I was reminded of 
> types.SimpleNamespace. This is nice, but I wanted to create a bag 
> class with constants that are read-only.

If you expect to specify the names of the constants ahead of time, the 
best solution is (I think) a namedtuple.

from collections import namedtuple
Bag = namedtuple('Bag', 'yes no dunno')
a = Bag(yes=1, no=0, dunno=42)
b = Bag(yes='okay', no='no way', dunno='not a clue')

ought to do what you want.

Don't make the mistake of doing this:

from collections import namedtuple
a = namedtuple('Bag', 'yes no dunno')(yes=1, no=0, dunno=42)
b = namedtuple('Bag', 'yes no dunno')(yes='okay', no='no way', dunno='not a clue')

because that's quite wasteful of memory: each of a and b belong to a 
separate hidden class, and classes are rather largish objects.


If you expect to be able to add new items on the fly, but have them 
read-only once set, that's a different story.


-- 
Steve


More information about the Tutor mailing list