python多次导入 [英] python import multiple times
问题描述
我想这是一个笼统的问题,如果没有在正确的地方发布,那么抱歉.
I suppose this is a general question so sorry if not posted in the right place.
例如,我有一个函数 a
导入 os
.如果我从另一个文件多次调用这个函数,我假设导入也会多次完成?有没有办法只导入不存在的模块?
Say for instance, I have a function a
which imports os
. If I was to call this function from another file multiple times I am assuming that the import would be done multiple times as well? Is there a way to only import the module if its not already present?
基本上,我有一个类调用从各种文件导入的多个函数,而不是导入整个文件,我认为只导入函数会更容易,但现在我想知道我是否会让自己头疼长期进口过剩.
Basically, I have a class which calls multiple functions imported from various files, instead of importing the whole file I thought it would be easier to import just the function but now I am wondering if I am going to give myself headaches in the long run with excess imports.
推荐答案
如 描述 在python文档中,当python看到一些import语句时,它会做以下事情:
As described in python documentation, when python see some import statement it does the following things:
- 如果模块已经导入,则检查一些全局表
- 如果没有导入模块,python 会导入它,创建模块对象并将新创建的模块对象放到全局表中
- 如果导入了模块,python 只获取模块对象
- 如果是
import foo
模块的名称foo
将是foo
- 如果是
import foo as bar
模块的名称foo
将是bar
- 如果它是
from foo import bar as baz
python 在模块foo
中找到函数(或其他)bar
并将这个函数绑定到姓名baz
- if it was
import foo
name for modulefoo
will befoo
- if it was
import foo as bar
name for modulefoo
will bebar
- if it was
from foo import bar as baz
python finds function (or whatever)bar
in modulefoo
and will bind this function to namebaz
所以每个模块只导入一次.
So each module is imported only one time.
为了更好地理解导入机制,我建议创建玩具示例.
To better understand import mechanics I would suggest to create toy example.
文件
module.py
:print("import is in progress") def foo(): pass
文件
main.py
:def foo(): print("before importing module") import module module.foo() print("after importing module") if __name__ == '__main__': foo() foo()
把上面的文件放到同一个目录下.当
module.py
被导入时,它会打印import is in progress
.当您启动main.py
时,它会尝试多次导入module
但输出将是:Put above files to the same directory. When
module.py
is being imported it printsimport is in progress
. When you launchmain.py
it will try to importmodule
several times but the output will be:before importing module import is in progress after importing module before importing module after importing module
因此导入实际上只发生一次.您可以调整这个玩具示例来检查您感兴趣的案例.
So import really happens only once. You can adjust this toy example to check cases that are interesting to you.
这篇关于python多次导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!