我是否必须重新加载 python 中的模块才能捕获更改?
Do I have to reload a module in python to capture changes?
我是 运行 python 3.6.4
(anaconda, spyder).
我是否需要重新加载用户定义的模块才能捕获更改?
例如,假设我编写了简单函数并将其保存在 test.py
文件中:
def plus5(x):
return x + 5
然后在 IPython 控制台中输入
import test as t
然后我将用户定义的函数更改为:
def plus5(x):
return x + 500
然后当我输入 IPython console
t.plus5(0)
它 returns 500 没有首先重新导入或重新加载模块。
如果我将函数名称从 plus5
更改为其他名称,那么我必须重新导入模块才能看到更改。但是当我更改函数语句时,它会自动捕获更改而无需重新导入模块
来自 Python 文档:
Note: For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload()
e.g. import importlib; importlib.reload(modulename)
.
这是 IPython 解释器名称 autoreload
中的一项功能。它有魔法命令 %autoreload
允许激活或停用此功能。它似乎是默认打开的,但我找不到证明这一点的东西。
正如 Megalng 所解释的,这是 IPython
解释器的内置功能,在默认的 Python
解释器中,您必须使用 importlib
来重新加载模块。这是默认的 python 解释器执行,
Python 3.6.2 (default, Sep 5 2017, 17:37:49)
[GCC 4.6.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>> import test as t
>>> t.plus5(0)
5
>>>
>>>
>>> #Changed function body to return x + 500
...
>>> t.plus5(0)
5
>>> import test as t
>>> t.plus5(0)
5
>>> #It had no affect, even importing again doesn't work.
...
>>> import importlib; importlib.reload(t)
<module 'test' from '~/test.py'>
>>>
>>> t.plus5(0)
500
>>> #Now it works !
...
>>>
如您所见,即使将函数体更改为 return x + 500
,它仍然为 t.plus5(0)
生成 5 的结果,甚至导入测试模块再次没有帮助。它仅在使用 importlib 重新加载测试模块时才开始工作。
我是 运行 python 3.6.4
(anaconda, spyder).
我是否需要重新加载用户定义的模块才能捕获更改?
例如,假设我编写了简单函数并将其保存在 test.py
文件中:
def plus5(x):
return x + 5
然后在 IPython 控制台中输入
import test as t
然后我将用户定义的函数更改为:
def plus5(x):
return x + 500
然后当我输入 IPython console
t.plus5(0)
它 returns 500 没有首先重新导入或重新加载模块。
如果我将函数名称从 plus5
更改为其他名称,那么我必须重新导入模块才能看到更改。但是当我更改函数语句时,它会自动捕获更改而无需重新导入模块
来自 Python 文档:
Note: For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use
importlib.reload()
e.g.
import importlib; importlib.reload(modulename)
.
这是 IPython 解释器名称 autoreload
中的一项功能。它有魔法命令 %autoreload
允许激活或停用此功能。它似乎是默认打开的,但我找不到证明这一点的东西。
正如 Megalng 所解释的,这是 IPython
解释器的内置功能,在默认的 Python
解释器中,您必须使用 importlib
来重新加载模块。这是默认的 python 解释器执行,
Python 3.6.2 (default, Sep 5 2017, 17:37:49)
[GCC 4.6.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>> import test as t
>>> t.plus5(0)
5
>>>
>>>
>>> #Changed function body to return x + 500
...
>>> t.plus5(0)
5
>>> import test as t
>>> t.plus5(0)
5
>>> #It had no affect, even importing again doesn't work.
...
>>> import importlib; importlib.reload(t)
<module 'test' from '~/test.py'>
>>>
>>> t.plus5(0)
500
>>> #Now it works !
...
>>>
如您所见,即使将函数体更改为 return x + 500
,它仍然为 t.plus5(0)
生成 5 的结果,甚至导入测试模块再次没有帮助。它仅在使用 importlib 重新加载测试模块时才开始工作。