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


当前回答

对于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.

其他回答

import sys

del sys.modules['module_name']
import module_name

另一个小问题:如果你使用import some_module作为sm语法,那么你必须用它的别名重新加载模块(本例中是sm):

>>> import some_module as sm
...
>>> import importlib
>>> importlib.reload(some_module) # raises "NameError: name 'some_module' is not defined"
>>> importlib.reload(sm) # works

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

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

虽然提供的答案确实适用于特定的模块,但它们不会重载子模块,如此答案所述:

如果一个模块使用from…从另一个模块导入对象进口…,为另一个模块调用reload()不会重定义从它导入的对象——一种解决方法是重新执行from语句,另一种方法是使用导入和限定名称(module.*name*)。

然而,如果使用__all__变量来定义公共API,则有可能自动重载所有公共可用的模块:

# Python >= 3.5
import importlib
import types


def walk_reload(module: types.ModuleType) -> None:
    if hasattr(module, "__all__"):
        for submodule_name in module.__all__:
            walk_reload(getattr(module, submodule_name))
    importlib.reload(module)


walk_reload(my_module)

在前面的回答中提到的警告仍然有效。值得注意的是,修改不属于__all__变量所描述的公共API的子模块不会受到使用该函数重新加载的影响。类似地,删除子模块的元素不会被重新加载反映出来。

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

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

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

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