Python Enum or Constants Class
In Brief:
This class will create write-once, read-many-times 'Constants' in Python.... more
Language
Python
# 's
1class Constants:
2
3 # A constant variable
4 foo = 1337
5
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
9
10 self.__dict__[attr] = value
This class will create write-once, read-many-times 'Constants' in Python.
It can be used like this:
>>> const = Constants() >>> const.test1 = 42 >>> const.test1 42 >>> const.test1 = 43 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in __setattr__ ValueError: Attribute test1 already has a value and so cannot be written to >>> const.test1 42
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.
Add a Comment