如何重新加载使用`from module import *`导入的python模块

在这个有用的问答中,我看到可以使用from whatever_module import *,或者在Python 3中可以使用whatever_module。

我的问题是,如果我说过from whatever_module import *要导入怎么办? 那么当我使用reload()时,我没有whatever_module可以引用。你们会因为把整个模块扔到全局名称空间中而对我大吼大叫吗? :)

8个解决方案

50 votes

我同意“一般不要这样做”的共识,但是...

正确答案是:

import X
reload(X)
from X import Y # or * for that matter
Catskul answered 2020-07-08T20:58:15Z
8 votes

切勿使用import *; 它破坏了可读性。

另外,请注意,重新加载模块几乎永远不会有用。 您无法预测重新加载模块后程序最终将处于何种状态,因此这是获取难以理解,无法再现的错误的好方法。

Allen answered 2020-07-08T20:58:39Z
4 votes

一个

from module import *

从module获取所有“导出的”对象,并将它们绑定到模块级(或您所使用的范围)的名称。 您可以将模块重新加载为:

reload(sys.modules['module'])

但这对您没有任何好处:无论您使用的是什么级别的名称,仍然指向旧对象。

tzot answered 2020-07-08T20:59:08Z

2 votes

更干净的答案是Catskul的好答案与Ohad Cohen的from X import Y的使用以及直接重新定义的混合:

import sys
Y = reload(sys.module["X"]).Y # reload() returns the new module

实际上,执行from X import Y会创建一个新符号(X),可以在随后的代码中对其进行重新定义,这是不必要的(而X是一个通用模块,因此不应发生)。

这里有趣的一点是from X import Y不会将X添加到名称空间,而是将模块X添加到已知模块列表(sys.modules),这允许重新加载该模块(并访问其新内容)。

更一般地,如果需要更新多个导入的符号,则这样更方便地导入它们:

import sys
reload(sys.module["X"]) # No X symbol created!
from X import Y, Z, T
Eric O Lebigot answered 2020-07-08T20:59:42Z
1 votes

我发现了另一种在导入时处理重新加载模块的方法:

from directory.module import my_func

很高兴知道一般如何导入模块。在sys.modules词典中搜索该模块。 如果它已经存在于sys.modules中-该模块将不会再次导入。

因此,如果我们想重新加载模块,只需将其从sys.modules中删除,然后再次导入即可:

import sys
from directory.module import my_func
my_func('spam')
# output: 'spam'
# here I have edited my_func in module.py
my_func('spam') # same result as above
#output: 'spam'
del sys.modules[my_func.__module__]
from directory.module import my_func
my_func('spam') # new result
#output: 'spam spam spam spam spam'

如果您希望在运行整个脚本时重新加载模块,则可以使用异常处理程序:

try:
del sys.modules[my_func.__module__]
except NameError as e:
print("""Can't remove module that haven't been imported.
Error: {}""".format(e))
from utils.module import my_func
..........
# code of the script here
ksiu answered 2020-07-08T21:00:15Z
0 votes

使用from whatever_module import whatever进行导入时,whatever被视为导入模块的一部分,因此要重新加载-您应该重新加载模块。 但是只要重新加载模块,您仍然会从已导入的whatever_module中获得旧的whatever-因此,您需要重新加载(whatever_module),然后重新加载模块:

# reload(whatever_module), if you imported it
reload(sys.modules['whatever_module'])
reload(sys.modules[__name__])
如果您使用from whatever_module import whatever,也可以考虑
whatever=reload(sys.modules['whatever_module']).whatever

要么

whatever=reload(whatever_module).whatever
Ohad Cohen answered 2020-07-08T21:00:44Z
0 votes
import re
for mod in sys.modules.values():
if re.search('name', str(mod)):
reload(mod)
jennifer answered 2020-07-08T21:01:00Z
-1 votes

对于python 3.7:

from importlib import reload #import function "reload"
import YourModule #import your any modules
reload(YourModule) #reload your module

可以从您自己的函数中调用重载函数

def yourFunc():
reload(YourModule)
Veniamin Magnet answered 2020-07-08T21:01:24Z