【问题标题】:How to define a python constant from a string key如何从字符串键定义python常量
【发布时间】:2020-09-23 14:12:10
【问题描述】:

我有一个在其__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 类对象,但是我总是必须通过该对象访问它们;不像在我的代码中简单地编写常量那么简洁。

或者还有其他更 Pythonic 的方式吗?

【问题讨论】:

    标签: python configuration constants


    【解决方案1】:

    要实现这一点,您应该在模块中创建变量,但由于您仅在运行时知道变量名称,因此您必须在模块上使用 setattr(您可以从 sys模块):

    import sys
    
    setattr(sys.modules[__name__], var_name, var_val)
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
    • 两个答案都有效。我最终使用了这个,因为代码的作用有点更明显,例如在模块上设置一个属性,使其能够被导入。
    【解决方案2】:

    您可以将它们添加到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
    

    【讨论】:

    • 感谢您指出builtins,到目前为止甚至都不知道他们。
    猜你喜欢
    • 2018-07-14
    • 2011-11-10
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2019-10-09
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多