If you have groups of related constants, such as the regex flags
, then an Enum
is the appropriate tool (e.g. your hi
and hello
in Set2
).
For unrelated constants I would use the Constant
class found in aenum
1:
class MiscellaneousConstants(Constant):
A = 1
B = 2
Constant
s are similar to Enum
s in that you cannot rebind them, and they have nice reprs:
>>> MiscellaneousConstants.A
<MiscellaneousConstants.A: 1>
>>> MiscellaneousConstants.A = 9
Traceback (most recent call last):
...
AttributeError: cannot rebind constant <MiscellaneousConstants.A>
Typing the class name can be a bother, so to facilitate getting the Constant
members into the global name space, export
is provided:
from aenum import Constant, export
@export(globals())
class MiscellaneousConstants(Constant):
A = 1
B = 2
and in use:
>>> A
<MiscellaneousConstants.A: 1>
Note that, as is normal for Python, names at the global level can still be rebound:
>>> A = 9
>>> A
9
Constant
class members, however, are still constant:
>>> MiscellaneousConstants.A
<MiscellaneousConstants.A: 1>
>>> MiscellaneousConstants.A = 9
Traceback (most recent call last):
...
AttributeError: cannot rebind constant <MiscellaneousConstants.A>
1 Disclosure: I am the author of the Python stdlib Enum
, the enum34
backport, and the Advanced Enumeration (aenum
) library.