重新加载本地模块不工作

2024-05-15 02:14:56 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我知道这个已经发布在上面了,但是要么A)建议不起作用,要么B)建议手动从命名空间中删除模块,然后像平常一样重新导入它。在

我有以下模块结构

basedir/
    pytools/
        __init__.py
        tools.py
    setup.py
    test.py

如果我在basedir,导入pytools,并创建一个testcls类的对象。类的实际属性在tools.py中找到。testcls有一个名为testfunc的方法,它现在只打印出AAA

^{pr2}$

假设我将testfunc()改为现在打印BBB。我这样做,并保存文件。然后我重新加载模块并重试,它不会打印出BBB

>>> from importlib import reload
>>> reload(pytools)
>>> test = pytools.testcls()
>>> test.testfunc()
AAA

但是如果我执行完全相同的过程,而不是更改test.py,将该文件作为模块导入,在其中编辑一个函数,然后重新加载,它的行为与预期一样:

>>> import test
>>> testvariable = test.testcls()
>>> testvariable.testfunc2()
AAA
# Change the function here
>>> from importlib import reload
>>> reload(test)
>>> testvariable = test.testcls()
>>> testvariable.testfunc2()
BBB

我真的不明白发生了什么事,只是现在真的很烦我。这也花了我不少时间,但我现在更恼火。在

你知道怎么回事吗??在

版本:

Python:3.6.5

翻译:IPython,6.2.1


Tags: 模块文件pytestimporttoolsreload建议
1条回答
网友
1楼 · 发布于 2024-05-15 02:14:56

让我们更笼统地命名:

basedir/
    testpackage/
        __init__.py
        testmodule.py
    test.py

如果测试模块.py包含:

^{pr2}$

然后,以下操作如您所期望的那样工作:

>>> from testpackage import testmodule
>>> obj = testmodule.TestClass()
>>> obj.test_method()
DDD
>>> # === Edit ===
>>> from importlib import reload
>>> reload(testmodule)
>>> obj = testmodule.TestClass()
>>> obj.test_method()
EEE

但是,如果__init__.py有类似于:

from .testmodule import TestClass

如果您尝试导入(并重新加载)包而不是模块,则会发生以下情况:

>>> import testpackage
>>> obj = testpackage.TestClass()
>>> obj.test_method()
EEE
>>> # === Edit ===
>>> from importlib import reload
>>> reload(testpackage)
>>> obj = testpackage.TestClass()
>>> obj.test_method()
EEE

(不变)

注意以下章节of the docs

If a module imports objects from another module using from … import …, calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.

如果您要重新加载模块和包,那么它将再次按您预期的方式工作:

>>> import testpackage
>>> obj = testpackage.TestClass()
>>> obj.test_method()
HHH
>>> # === Edit ===
>>> from importlib import reload
>>> reload(testpackage.testmodule)
>>> reload(testpackage)
>>> obj = testpackage.TestClass()
>>> obj.test_method()
III

但这似乎很愚蠢,而且容易出错,只需使用第一个示例中的方法:

from testpackage import testmodule
...
reload(testmodule)
... 

相关问题 更多 >

    热门问题