我正在寻找一种使用Python定义多个相关常量的方法,这些常量可以在多个模块中使用,并且希望它们保存在单个文件中。我想出了几种选项,但它们都有缺点。
方法1-简单的全局常量
# file resources/resource_ids.py
FOO_RESOURCE = 'foo'
BAR_RESOURCE = 'bar'
BAZ_RESOURCE = 'baz'
QUX_RESOURCE = 'qux'
# file runtime/bar_handler.py
from resources.resource_ids import BAR_RESOURCE
# ...
def my_code():
value = get_resource(BAR_RESOURCE)
这是一种简单且通用的方法,但也有一些缺点:
- 需要在所有常量名称后添加
_RESOURCE
以提供上下文。 - 在IDE中检查常量名称将不会显示其他常量值。
方法2 - 枚举
# file resources/resource_ids.py
from enum import Enum, unique
@unique
class ResourceIds(Enum):
foo = 'foo'
bar = 'bar'
baz = 'baz'
qux = 'qux'
# file runtime/bar_handler.py
from resources.resource_ids import ResourceIds
# ...
def my_code():
value = get_resource(ResourceIds.bar.value)
这种方法解决了第一种方法的问题,但这种解决方案的缺点是需要使用.value
来获取字符串表示形式(假设我们需要字符串值而不仅是一致的枚举值)。如果未附加.value
,可能会导致难以调试的运行时问题。
第三种方法 - 类变量
# file resources/resource_ids.py
class ResourceIds:
foo = 'foo'
bar = 'bar'
baz = 'baz'
qux = 'qux'
# file runtime/bar_handler.py
from resources.resource_ids import ResourceIds
# ...
def my_code():
value = get_resource(ResourceIds.bar)
这种方法是我最喜欢的,但可能会被误解 - 类是用来实例化的。虽然使用类的实例而不是类本身不会影响代码正确性,但我想避免这种浪费。
这种方法的另一个缺点是值实际上并不是常量。任何代码客户端都可以潜在地改变它们。
有可能防止一个类被实例化吗?我是否忽略了某些将密切相关的常量分组的惯用方法?
d = {ResourceIds.foo: 'foo_value'} print(d['foo']) # 输出 "foo_value"
- EvilTosha