如何在 Python 中重新加载模块的功能? [英] How to reload a module's function in Python?

查看:22
本文介绍了如何在 Python 中重新加载模块的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

跟进有关重新加载模块的问题, 如何从更改的模块重新加载特定功能?

Following up on this question regarding reloading a module, how do I reload a specific function from a changed module?

伪代码:

from foo import bar

if foo.py has changed:
    reload bar

推荐答案

你想要的都是可能的,但是需要重新加载两件事...首先reload(foo),然后你也必须reload(baz)(假设 baz 是包含 from foo import bar 语句的模块的名称).

What you want is possible, but requires reloading two things... first reload(foo), but then you also have to reload(baz) (assuming baz is the name of the module containing the from foo import bar statement).

至于为什么... 当 foo 首次加载时,会创建一个 foo 对象,其中包含一个 bar 对象.当您将 bar 导入 baz 模块时,它会存储对 bar 的引用.当 reload(foo) 被调用时,foo 对象被清空,并且模块重新执行.这意味着所有 foo 引用仍然有效,但是已经创建了一个新的 bar 对象...因此所有已导入某处的引用仍然是对 的引用旧 bar 对象.通过重新加载 baz,您会使其重新导入新的 bar.

As to why... When foo is first loaded, a foo object is created, containing a bar object. When you import bar into the baz module, it stores a reference to bar. When reload(foo) is called, the foo object is blanked, and the module re-executed. This means all foo references are still valid, but a new bar object has been created... so all references that have been imported somewhere are still references to the old bar object. By reloading baz, you cause it to reimport the new bar.

或者,您可以在模块中执行 import foo,并始终调用 foo.bar().这样,每当您 reload(foo) 时,您都会获得最新的 bar 引用.

Alternately, you can just do import foo in your module, and always call foo.bar(). That way whenever you reload(foo), you'll get the newest bar reference.

注意:从 Python 3 开始,需要先导入 reload 函数,通过 from importlib import reload

NOTE: As of Python 3, the reload function needs to be imported first, via from importlib import reload

这篇关于如何在 Python 中重新加载模块的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆