[Python-ideas] Support other dict types for type.__dict__
sven at marnach.net
Tue Feb 28 00:39:06 CET 2012
An easy way to create immutable instances is 'collections.namedtuple':
X = namedtuple("X", "a b")
x = X(a=4, b=2)
x.a + x.b # fine
x.a = 5 # AttributeError: can't set attribute
x.c = 5 # AttributeError: 'X' object has no attribute 'c'
Tricks using 'object.__setattr__()' etc. will fail since the instance
doesn't have a '__dict__'. The only data in the instance is stored in
a tuple, so it's as immutable as a tuple.
You can also derive from 'X' to add further methods. Remember to set
'__slots__' to an empty iterable to maintain immutability.
More information about the Python-ideas