【问题标题】:How can I override a constant in an imported Python module?如何覆盖导入的 Python 模块中的常量?
【发布时间】:2012-09-11 20:14:22
【问题描述】:

在我的应用程序中,我使用包 example 中的模块,称为 examplemod

我的应用:

from example import examplemod
examplemod.do_stuff()

它像这样在example 中导入另一个模块。

examplemod.py:

from example import config
# uses config
# then does stuff

config 使用常量。

config.py:

CONSTANT = "Unfortunate value"

当我在我的应用程序中使用examplemod(将其设置为CONSTANT = "Better value")时,我想覆盖这个常量,并且我不想修改底层模块,所以我不必维护我的自己的包。我该怎么做?

【问题讨论】:

  • 我可能是错的,但我认为您可以在导入变量后为其赋值。

标签: python module python-import


【解决方案1】:

是的,但只有在完全限定的模块访问路径下才能按预期工作:

import example
example.examplemod.config.CONSTANT = "Better value"
example.examplemod.do_stuff()

【讨论】:

  • 另外值得一提的是,如果 examplemod 模块使用 from config import CONSTANT 语法将 CONSTANT 直接导入其符号表,您需要执行 example.examplemod.CONSTANT = "Better value",因为 examplemod 将拥有自己对 CONSTANT 的引用.您使用的表单替换了 config.CONSTANT,这在 examplemod 模块使用 from examplemod import config; config.CONSTANT 的情况下有效。
【解决方案2】:

谢谢大家的回答。他们为我指明了正确的方向,尽管他们都没有按书面规定工作。我最终做了以下事情:

import example.config
example.config.CONSTANT = "Better value"

from example import examplemod
examplemod.do_stuff()
# desired result!

(另外,我正在向模块维护者提交一个补丁,以使 CONSTANT 成为可配置的选项,因此我不必这样做,但同时需要安装 stock 模块。)

【讨论】:

    【解决方案3】:

    这称为monkey patching,虽然不是首选,但如果有其他方法可以完成相同的事情,它是相当常见的:

    examplemod.config.CONSTANT = "Better value"
    

    问题是您依赖 examplemodconfig 的内部保持不变,因此如果任一模块发生更改,这可能会中断。

    【讨论】:

      【解决方案4】:

      我不确定这是否足够,但你尝试过吗:

      from example import config
      config.CONSTANT = "A desirable value"
      

      确保在导入 examplemod 之前执行此操作。这应该可行,因为 python 缓存了导入,因此您修改的 config 将与 examplemod 获得的相同。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 2016-04-05
        • 2021-07-15
        • 1970-01-01
        • 1970-01-01
        • 2020-03-04
        相关资源
        最近更新 更多