如何从字符串键定义 python 常量
How to define a python constant from a string key
我有一个模块,其 __init__.py
中定义了常量。我想读入配置文件并根据这些配置内容定义常量。有没有办法从字符串键定义常量,像这样:
__init__py
:
config = { "FOO": "BAR" }
for key, value in config.items():
define(key, value) # <- "define" is what I am looking for
foo.py
:
from . import FOO
print(FOO)
> BAR
我还考虑过一个具有这些常量的 Config class 对象,但是我总是必须通过该对象访问它们;不像在我的代码中简单地写常量那么整洁。
或者还有其他更像 Python 的方法吗?
要实现这一点,您应该在模块中创建变量,但由于您只知道 run-time 上的变量名称,因此您必须在模块上使用 setattr
(您可以从 sys
模块访问):
import sys
setattr(sys.modules[__name__], var_name, var_val)
您可以将它们添加到 builtins:
import builtins
config = { "FOO": "BAR" }
for key, value in config.items():
# I prefer to have them prefixed, to make sure not overwriting existing values!
setattr(builtins, 'cfg_%s' % key, value)
# available everywhere (other modules as well)
print(cfg_FOO)
输出:
BAR
我有一个模块,其 __init__.py
中定义了常量。我想读入配置文件并根据这些配置内容定义常量。有没有办法从字符串键定义常量,像这样:
__init__py
:
config = { "FOO": "BAR" }
for key, value in config.items():
define(key, value) # <- "define" is what I am looking for
foo.py
:
from . import FOO
print(FOO)
> BAR
我还考虑过一个具有这些常量的 Config class 对象,但是我总是必须通过该对象访问它们;不像在我的代码中简单地写常量那么整洁。
或者还有其他更像 Python 的方法吗?
要实现这一点,您应该在模块中创建变量,但由于您只知道 run-time 上的变量名称,因此您必须在模块上使用 setattr
(您可以从 sys
模块访问):
import sys
setattr(sys.modules[__name__], var_name, var_val)
您可以将它们添加到 builtins:
import builtins
config = { "FOO": "BAR" }
for key, value in config.items():
# I prefer to have them prefixed, to make sure not overwriting existing values!
setattr(builtins, 'cfg_%s' % key, value)
# available everywhere (other modules as well)
print(cfg_FOO)
输出:
BAR