|In Brief||This class will create write-once, read-many-times 'Constants' in Python.... more|
3 # A constant variable
4 foo = 1337
6 def __setattr__(self, attr, value):
7 if hasattr(self, attr):
8 raise ValueError, 'Attribute %s already has a value and so cannot be written to' % attr
10 self.__dict__[attr] = value
This class will create write-once, read-many-times 'Constants' in Python.
It can be used like this:
1>>> const = Constants()
2>>> const.test1 = 42
5>>> const.test1 = 43
6Traceback (most recent call last):
7 File "<stdin>", line 1, in <module>
8 File "<stdin>", line 4, in __setattr__
9ValueError: Attribute test1 already has a value and so cannot be written to
To have a completely read-only class, that behaves like an enum data type, remove the if statement and have __setattr__ always raise an error. Obviously in this case you would need to completely initialize all the variables inside the class definition.
Read Python __Underscore__ Methods for more information about __setattr__.