Python - 优化导入和几个脚本
Python - Optimizing imports and several scripts
假设我有一个声明以下导入的脚本:
import some_library
稍后在代码中我有以下内容:
def foobar():
import foo
foo.bar()
但是,foo
也导入 some_library
(并且依赖于它)我将如何着手优化这种情况?是不是直接在导入foo
代码的class里面写bar()
代码?或者是否有任何其他方法不必在 foo
片段中导入 some_library
代码,因为它已经在 "outer class" 中?我可以在构造函数中发送对库的引用吗?
这已经由 Python 运行时完成 - 命令 import
首先检查所需的模块是否不存在(它们都可以在 sys.modules
字典中列出) - 只有当它不存在时,才会触发实际导入。
之后,您要求的名称将在放置导入命令的名称空间中可用。
来自 the docs:"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."
假设我有一个声明以下导入的脚本:
import some_library
稍后在代码中我有以下内容:
def foobar():
import foo
foo.bar()
但是,foo
也导入 some_library
(并且依赖于它)我将如何着手优化这种情况?是不是直接在导入foo
代码的class里面写bar()
代码?或者是否有任何其他方法不必在 foo
片段中导入 some_library
代码,因为它已经在 "outer class" 中?我可以在构造函数中发送对库的引用吗?
这已经由 Python 运行时完成 - 命令 import
首先检查所需的模块是否不存在(它们都可以在 sys.modules
字典中列出) - 只有当它不存在时,才会触发实际导入。
之后,您要求的名称将在放置导入命令的名称空间中可用。
来自 the docs:"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."