gpt4 book ai didi

Python:优化模块导入

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:57 25 4
gpt4 key购买 nike

这是一个理论问题,我一段时间以来一直在寻找答案,但从未真正找到它。

假设我有我的主文件main.py,其中包含import numpy as npimport helper

如果我有一个帮助文件 helper.py,我可以在 helper.py 中使用 np 吗,因为我已经将它导入到 main.py,我唯一一次使用 helper.py 是通过 main.py,结果是 numpy > 总是被导入?

最佳答案

没有。 python documentation状态:

The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope.

如果导入发生在模块的顶部,则本地范围将是全局的 - 即模块的本地范围

从好的方面来说,通常导入只会发生一次。 Python 将在执行导入之前在缓存中搜索导入,如果找到,将创建对先前导入的模块的引用。这保存了必须加载第二个副本 - 在两个模块中都包含 import 语句(通常)没有什么坏处。

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.

此外,来自FAQs :

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application;

关于Python:优化模块导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38464124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com