Python Enum or Constants Class Atom Feed 0

In Brief This class will create write-once, read-many-times 'Constants' in Python.... more
# '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:

# 's
 1>>> const = Constants()
2>>> const.test1 = 42
3>>> const.test1
442
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
10>>> const.test1
1142

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__.