Python - Best/cleanest Way To Define Constant Lists Or Dictionarys
Solution 1:
Put your constants into their own module:
# constants.pyRED = 1BLUE = 2GREEN = 3
Then import that module and use the constants:
import constants
print"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.
Solution 2:
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.
Solution 3:
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.
Solution 4:
If you want to mess with nested constants and don't like dicts, I came up with this fun solution:
# Recursively transform a dict to instances of the desired classimport json
from collections import namedtuple
classDictTransformer():
@classmethoddefconstantize(self, d):
return self.transform(d, klass=namedtuple, klassname='namedtuple')
@classmethoddeftransform(self, d, klass, klassname):
return self._from_json(self._to_json(d), klass=klass, klassname=klassname)
@classmethoddef_to_json(self, d, access_method='__dict__'):
return json.dumps(d, default=lambda o: getattr(o, access_method, str(o)))
@classmethoddef_from_json(self, jsonstr, klass, klassname):
return json.loads(jsonstr, object_hook=lambda d: klass(klassname, d.keys())(*d.values()))
Ex:
constants = {
'A': {
'B': {
'C': 'D'
}
}
}
CONSTANTS = DictTransformer.transform(d, klass=namedtuple, klassname='namedtuple')
CONSTANTS.A.B.C == 'D'
Pros:
- handles nested dicts
- can potentially generate other types of dicts/classes
- namedtuples provide immutability for constants
Cons:
- may not respond to .keys and .values if those are not provided on your klass (though you can sometimes mimic with ._fields and list(A.B.C))
Thoughts?
h/t to @hlzr and you guys for the original class idea
Solution 5:
Accepted answer is fine, to take it one step further can use typings when defining your constants; you could just specify Final, or go a step further and provide Final[type] as well, e.g.:
from typing import Final, List
CONSTANT1: Final = 'asd'
CONSTANT_FOO: Final[int] = 123
ADLS_ENVIRONMENTS: Final[List[str]] = ["sandbox", "dev", "uat", "prod"]
# etc.
See https://www.python.org/dev/peps/pep-0591/#the-final-annotation
Post a Comment for "Python - Best/cleanest Way To Define Constant Lists Or Dictionarys"