如何覆盖导入的Python模块中的常量? [英] How can I override a constant in an imported Python module?
问题描述
在我的应用程序中,我正在使用名为examplemod
的软件包example
中的模块.
In my application I am using module within the package example
called examplemod
.
我的应用:
from example import examplemod
examplemod.do_stuff()
它会像这样在example
内导入另一个模块.
It imports another module within example
like so.
examplemod.py:
from example import config
# uses config
# then does stuff
config
使用常量.
config.py:
CONSTANT = "Unfortunate value"
当我在应用程序中使用examplemod
(将其设置为CONSTANT = "Better value"
)时,我想覆盖此常量,并且我不想更改底层模块,因此不必维护我的常量.自己的包裹.我该怎么办?
I'd like to override this constant when I'm using examplemod
in my application (setting it to CONSTANT = "Better value"
) and I'd prefer not to modify the underlying module so I don't have to maintain my own package. How can I do this?
推荐答案
谢谢大家的回答.尽管他们都没有按书面要求工作,但他们向我指出了正确的方向.我最终做了以下事情:
Thank you all for your answers. They pointed me in the right direction though none of them worked as written. I ended up doing the following:
import example.config
example.config.CONSTANT = "Better value"
from example import examplemod
examplemod.do_stuff()
# desired result!
(此外,我正在向模块维护者提交补丁,以使CONSTANT成为可配置的选项,因此我不必这样做,但同时需要安装标准模块.)
这篇关于如何覆盖导入的Python模块中的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!