繁体   English   中英

我是否必须在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控制台时

t.plus5(0) it returns 500 without re-import或首先重新加载模块。

如果我将函数名称从“plus5”更改为其他内容,那么我必须重新导入模块以查看更改。 但是当我更改函数语句时,它会自动捕获更改而无需重新导入模块

来自python文档:“注意出于效率原因,每个解释器会话只导入一个模块。因此,如果更改模块,则必须重新启动解释器 - 或者,如果只是一个模块要进行交互式测试,请使用importlib.reload()

例如import importlib; importlib.reload(modulename) import importlib; importlib.reload(modulename) 。“

这是IPython解释器名称autorealod中的一个功能。 它具有魔术命令%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重新加载测试模块时才开始工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM