如何重新导入模块?我想在对其.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.
在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更改。
虽然提供的答案确实适用于特定的模块,但它们不会重载子模块,如此答案所述:
如果一个模块使用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的子模块不会受到使用该函数重新加载的影响。类似地,删除子模块的元素不会被重新加载反映出来。
如果你想从一个模块中导入一个特定的函数或类,你可以这样做:
import importlib
import sys
importlib.reload(sys.modules['my_module'])
from my_module import my_function
另一个小问题:如果你使用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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录