Skip to main content
 首页 » 编程设计

python之循环导入的函数中的模块导入会循环导入吗

2025年05月04日20sxdcgaq8080

我还没有达到拥有工具(或知道如何开发或使用它们)来测试和分析看似简单的事情(例如我的问题)的水平,所以我求助于您。

我有一个检查条件的函数,并根据该条件选择最好的数学工具来处理(不同的模块),但这个函数应用于数组的窗口,因此是循环的。窗口与窗口之间可能会发生不同的导入,但这让我想知道导入是否真的在循环,这是否是一个性能问题。

这是来自 matplotlib 源代码的示例

def pause(interval): 
    """ 
    Pause for *interval* seconds. 
 
    If there is an active figure it will be updated and displayed, 
    and the GUI event loop will run during the pause. 
 
    If there is no active figure, or if a non-interactive backend 
    is in use, this executes time.sleep(interval). 
 
    This can be used for crude animation. For more complex 
    animation, see :mod:`matplotlib.animation`. 
 
    This function is experimental; its behavior may be changed 
    or extended in a future release. 
 
    """ 
    backend = rcParams['backend'] 
    if backend in _interactive_bk: 
        figManager = _pylab_helpers.Gcf.get_active() 
        if figManager is not None: 
            canvas = figManager.canvas 
            canvas.draw() 
            show(block=False) 
            canvas.start_event_loop(interval) 
            return 
 
    # No on-screen figure is active, so sleep() is all we need. 
    import time 
    time.sleep(interval) 

如果我在一个循环中交替打开和关闭数字,时间是否会每隔一次迭代导入一次?或者只是在第一次调用导入时导入而忽略后续导入?

谢谢

请您参考如下方法:

import 成功完成后,导入的模块缓存在 sys.modules 中,随后的 import 语句将在 中找到该模块>sys.modules 所以模块不会被重新导入。您可以使用 reload 内置函数强制重新导入模块。

来自 the documentation :

The first place checked during import search is sys.modules. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. So if foo.bar.baz was previously imported, sys.modules will contain entries for foo, foo.bar, and foo.bar.baz.

PEP 8 (Python 风格指南)建议导入应该在文件的顶部,而不是在方法中。违反此规则(给出“延迟导入”)的正当理由是,如果模块导入很昂贵并且在您的程序中很少使用(并且在典型执行中根本不使用),或者解决循环导入依赖性(尽管在那如果你应该尝试通过更好地拆分模块功能来解决循环问题)。对于像 time 这样的内置于 Python 中的模块,几乎没有理由使用延迟导入。