Python - Best/Cleanest way to define constant lists or dictionarys
Put your constants into their own module:
# constants.pyRED = 1BLUE = 2GREEN = 3
Then import that module and use the constants:
import constantsprint "RED is", constants.RED
The constants can be any value you like, I've shown integers here, but lists and dicts would work just the same.
Usually I do this:
File: constants.py
CONSTANT1 = 'asd'CONSTANT_FOO = 123CONSTANT_BAR = [1, 2, 5]
File: your_script.py
from constants import CONSTANT1, CONSTANT_FOO# or if you want *all* of them# from constants import *...
Now your constants are in one file and you can nicely import and use them.
Make a separate file constants.py
, and put all globally-relevant constants in there. Then you can import constants
to refer to them as constants.SPAM
or do the (questionable) from constants import *
to refer to them simply as SPAM
or EGGS
.
While we're here, note that Python doesn't support constant constants. The convention is just to name them in ALL_CAPS
and promise not to mutate them.