小编Evi*_*sha的帖子

Python中与组相关的常量

我正在寻找一种Python式的方法来在单个文件中定义多个相关常量以在多个模块中使用。我想出了多种选择,但它们都有缺点。

方法 1 - 简单的全局常量

# file resources/resource_ids.py

FOO_RESOURCE = 'foo'
BAR_RESOURCE = 'bar'
BAZ_RESOURCE = 'baz'
QUX_RESOURCE = 'qux'
Run Code Online (Sandbox Code Playgroud)
# file runtime/bar_handler.py

from resources.resource_ids import BAR_RESOURCE

# ...

def my_code():
  value = get_resource(BAR_RESOURCE)
Run Code Online (Sandbox Code Playgroud)

这很简单且通用,但有一些缺点:

  • _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'
Run Code Online (Sandbox Code Playgroud)
# file runtime/bar_handler.py

from resources.resource_ids import ResourceIds

# ...

def my_code():
  value = get_resource(ResourceIds.bar.value)
Run Code Online (Sandbox Code Playgroud)

这解决了第一种方法的问题,但该解决方案的缺点是需要使用 …

python enums python-class

8
推荐指数
1
解决办法
1592
查看次数

标签 统计

enums ×1

python ×1

python-class ×1