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

发布于 2024-10-29 08:06:31 字数 340 浏览 3 评论 0原文

我在这个有用的问答中看到,人们可以使用reload(whatever_module)或者, Python 3,imp.reload(whatever_module)

我的问题是,如果我说 fromwhatever_module import * 导入呢?然后当我使用 reload() 时,我没有 whatever_module 可以引用。你们会因为我把整个模块扔到全局命名空间中而对我大喊大叫吗? :)

I saw in this useful Q&A that one can use reload(whatever_module) or, in Python 3, imp.reload(whatever_module).

My question is, what if I had said from whatever_module import * to import? Then I have no whatever_module to refer to when I use reload(). Are you guys gonna yell at me for throwing a whole module into the global namespace? :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

蔚蓝源自深海 2024-11-05 08:06:31

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

正确的答案是:

from importlib import reload
import X
reload(X)
from X import Y  # or * for that matter

I agree with the "don't do this generally" consensus, but...

The correct answer is:

from importlib import reload
import X
reload(X)
from X import Y  # or * for that matter
木槿暧夏七纪年 2024-11-05 08:06:31

一个更清晰的答案是 Catskul 的好答案和 Ohad Cohen 对 sys.modules 的使用和直接重新定义的结合:

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

事实上,执行 import X 会创建一个新符号 (X)可能会在后面的代码中重新定义,这是不必要的(而 sys 是一个公共模块,所以这种情况不应该发生)。

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

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

import sys
reload(sys.modules["X"])  # No X symbol created!
from X import Y, Z, T

A cleaner answer is a mix of Catskul's good answer and Ohad Cohen's use of sys.modules and direct redefinition:

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

In fact, doing import X creates a new symbol (X) that might be redefined in the code that follows, which is unnecessary (whereas sys is a common module, so this should not happen).

The interesting point here is that from X import Y does not add X to the namespace, but adds module X to the list of known modules (sys.modules), which allows the module to be reloaded (and its new contents accessed).

More generally, if multiple imported symbols need to be updated, it is then more convenient to import them like this:

import sys
reload(sys.modules["X"])  # No X symbol created!
from X import Y, Z, T
孤寂小茶 2024-11-05 08:06:31

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

另外,请注意,重新加载模块几乎没有用。您无法预测重新加载模块后程序最终会处于什么状态,因此这是获得难以理解、无法重现的错误的好方法。

Never use import *; it destroys readability.

Also, be aware that reloading modules is almost never useful. You can't predict what state your program will end up in after reloading a module, so it's a great way to get incomprehensible, unreproduceable bugs.

西瓜 2024-11-05 08:06:31

A

from module import *

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

reload(sys.modules['module'])

但这不会给您带来任何好处:无论您的范围是级别的名称仍然指向旧对象。

A

from module import *

takes all “exported” objects from module and binds them to module-level (or whatever-your-scope-was-level) names. You can reload the module as:

reload(sys.modules['module'])

but that won't do you any good: the whatever-your-scope-was-level names still point at the old objects.

最近可好 2024-11-05 08:06:31

我找到了另一种方法来处理导入时重新加载模块的问题,例如:

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

I've found another way to deal with reloading a module when importing like:

from directory.module import my_func

It's nice to know how do modules are being imported generally.
The module is searched in sys.modules dictionary. If it already exists in sys.modules - the module will not be imported again.

So if we would like to reload our module, we can just remove it from sys.modules and import again:

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'

If You would like to get reloaded module when running whole script, you could use exception handler:

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
腹黑女流氓 2024-11-05 08:06:31

当使用 fromwhatever_module importwhat 导入时,whatever 被算作导入模块的一部分,因此要重新加载它 - 您应该重新加载您的模块。但是只要重新加载你的模块,你仍然会从已经导入的 whatever_module 中得到旧的 whatever,所以你需要重新加载(whatever_module),然后重新加载你的模块:

# reload(whatever_module), if you imported it
reload(sys.modules['whatever_module'])
reload(sys.modules[__name__])

如果您使用了 fromwhatever_module importwhat 您也可以考虑

whatever=reload(sys.modules['whatever_module']).whatever

whatever=reload(whatever_module).whatever

When importing using from whatever_module import whatever, whatever is counted as part of the importing module, so to reload it - you should reload your module. But just reloading your module you will still get the old whatever - from the already-imported whatever_module, so you need to reload(whatever_module), and than reload your module:

# reload(whatever_module), if you imported it
reload(sys.modules['whatever_module'])
reload(sys.modules[__name__])

if you used from whatever_module import whatever you can also consider

whatever=reload(sys.modules['whatever_module']).whatever

or

whatever=reload(whatever_module).whatever
み青杉依旧 2024-11-05 08:06:31
import re

for mod in sys.modules.values():
    if re.search('name', str(mod)):
        reload(mod)
import re

for mod in sys.modules.values():
    if re.search('name', str(mod)):
        reload(mod)
后知后觉 2024-11-05 08:06:31

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

for python 3.7 :

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

Reload function can be called from your own function

def yourFunc():
   reload(YourModule)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文