我们可以设置可以在会话中修改的模块级别属性吗

时间:2019-02-13 23:08:20

标签: python python-3.x

我正在尝试向配置文件添加模块级属性,并希望执行类似的操作。

# repo/__init__.py file
pass

# repo/config.py file
VERIFY_CERTS = True

然后在其他子模块中使用此变量

# repo/example.py
from repo.config import VERIFY_CERTS
def do_something():
    if VERIFY_CERTS:
        do something..
    else:
        do something else

现在,当我在另一个脚本中使用此repo模块时,我希望能够做到:

from repo.config import VERIFY_CERTS
VERIFY_CERTS = False
from repo.example import do_something
do_something()

有可能做这样的事情吗?

编辑:绝对不是Immutable vs Mutable types的重复,因为它讨论了关于可变和不可变数据类型的内容,而这是关于具有在会话中可以记住的模块级别属性。 修改了变量名以阐明为什么要这样做。

1 个答案:

答案 0 :(得分:0)

问题

据我了解,您想更改VERIFY_CERTS使用的do_something()的值。

首先,您的示例可以这样简化:

example.py

VERIFY_CERTS = True
def do_something():
    print(VERIFY_CERTS)

test.py

from example import do_something
VERIFY_CERTS = False
do_something()

运行test.py将打印True


解决方案

test.py中,只需导入整个模块example(无论如何,这都是导入的最佳做法),然后设置example.VERIFY_CERTS

import example
example.VERIFY_CERTS = False
example.do_something()

运行此命令将打印False

相关问题