1

Have a .py file with below content ?

class Set1(Enum):
   A = 1
   B = 2

class Set2(Enum):
  hi=1
  hello=2

OR simply

Set1 = {"A":1,"B":2}
Set2 = {"C"="hi","D"="Hello"}

Please note that these constants will be used by different modules in the project.

  • One way would to create ``constants.py`` file with all the constants as shown here, https://stackoverflow.com/questions/6343330/importing-a-long-list-of-constants-to-a-python-file – sushanth May 29 '20 at 07:39

2 Answers2

2

Usually, you define constants in a file like this:

some_file.py :

FOO = 0
BAR = "baz"

And if you need to use it:

import some_file

print(some_file.FOO)
print(some_file.BAR)
Blusky
  • 3,470
  • 1
  • 19
  • 35
  • So use of enum makes sense only when constants are related to one another in terms of order or sequence right ? – cool_heisenberg May 29 '20 at 08:00
  • 1
    @ShubhamPandey enums make sense when you need *an enumerated type*. So yes, they are some set of objects that are related, and they are all the same type.\ – juanpa.arrivillaga May 29 '20 at 08:02
0

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 aenum1:

class MiscellaneousConstants(Constant):
    A = 1
    B = 2

Constants are similar to Enums 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.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237