如何覆盖导入的 Python 模块中的常量? [英] How can I override a constant in an imported Python module?

查看:18
本文介绍了如何覆盖导入的 Python 模块中的常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆