如何重新导入模块?我想在对其.py文件进行更改后重新导入一个模块。


当前回答

如果你想从一个模块中导入一个特定的函数或类,你可以这样做:

import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function

其他回答

对于Python 3.4+:

import importlib
importlib.reload(nameOfModule)

对于Python < 3.4:

reload(my.module)

来自Python文档

重新加载以前导入的模块。参数必须是一个模块对象,因此它必须之前已成功导入。如果您已经使用外部编辑器编辑了模块源文件,并且希望在不离开Python解释器的情况下试用新版本,那么这很有用。

不要忘记使用这种方法的注意事项:

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed. 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. If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

在python 3中,重载不再是一个内置函数。

如果你正在使用python 3.4+,你应该使用reload from importlib库来代替:

import importlib
importlib.reload(some_module)

如果你使用的是python 3.2或3.3,你应该:

import imp  
imp.reload(module)  

代替。看到http://docs.python.org/3.0/library/imp.html imp.reload

如果你正在使用ipython,一定要考虑使用autoreload扩展:

%load_ext autoreload
%autoreload 2

实际上,在Python 3中,模块imp被标记为DEPRECATED。至少3.4是这样的。

相反,应该使用importlib模块中的reload函数:

https://docs.python.org/3/library/importlib.html#importlib.reload

但是请注意,这个库在上两个小版本中有一些api更改。

如果你想从一个模块中导入一个特定的函数或类,你可以这样做:

import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
import sys

del sys.modules['module_name']
import module_name