简体   繁体   English

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

[英]Will module import in function that is looped loop the import?

I am not yet at the level where I have tools (or know how to develop or use them) for testing and profiling seemingly simple things like my questions so I turn to you.我还没有达到我拥有工具(或知道如何开发或使用它们)的水平来测试和分析看似简单的事情,比如我的问题,所以我转向你。

I have a function that checks a condition and based on that condition picks the best mathematical tool to work with (different modules) but this function is applied on windows of an array and so is looped.我有一个检查条件的函数,并根据该条件选择最好的数学工具来处理(不同的模块),但该函数应用于数组的窗口,因此循环。 Different imports may occur from window to window but this leads me to wonder if the imports are actually being looped and if this is a performance issue at all.从一个窗口到另一个窗口可能会发生不同的导入,但这让我想知道导入是否实际上是循环的,这是否是一个性能问题。

Here is an example from the matplotlib source这是来自 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)

If I in a loop alternate opening and closing figures will time be imported every other iteration?如果我在循环中交替打开和关闭数字是否会每隔一次迭代导入时间? Or just imported the first time the import is called on and subsequent imports ignored?或者只是在第一次调用导入时导入而随后的导入被忽略?

Thanks谢谢

After an import completes successfully, the imported module is cached in sys.modules and subsequent import statements will find the module in sys.modules so the module will not be reimported. import成功完成后,导入的模块会缓存在sys.modules ,后续的import语句将在sys.modules找到该模块,因此不会重新导入该模块。 You can force a module reimport with the reload builtin function.您可以使用reload内置函数强制重新导入模块。

Fromthe documentation :文档

The first place checked during import search is sys.modules .在导入搜索期间检查的第一个位置是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 .因此,如果之前导入了foo.bar.baz ,则sys.modules将包含foofoo.barfoo.bar.baz条目。

PEP 8 (the Python style guide) recommends that imports should be at the top of the file, not within methods. PEP 8 (Python 风格指南)建议导入应该在文件的顶部,而不是在方法中。 Valid reasons to break this rule (giving a "late import") are if a module import is expensive and used only rarely in your program (and not at all in a typical execution), or to resolve a circular import dependency (though in that case you should try to resolve the circularity by splitting module functionality better).打破此规则(给出“延迟导入”)的有效理由是,如果模块导入代价高昂并且在您的程序中很少使用(并且在典型的执行中根本不使用),或者解决循环导入依赖(尽管在那种情况下)如果您应该尝试通过更好地拆分模块功能来解决循环问题)。 For a module like time , that is built in to Python, there's very little reason to use a late import.对于像time这样内置于 Python 的模块,几乎没有理由使用延迟导入。

The actual action of import only happens once (which is why you explicitly need to reload when you do want it to be imported again) -- the interpreter checks to see if it's already been imported. import的实际操作只发生一次(这就是为什么当您确实希望再次导入它时明确需要reload原因)——解释器检查它是否已经被导入。

But it is usually more pythonic to put all of your imports at the top of the module.但是将所有导入放在模块顶部通常更加Pythonic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM