简体   繁体   English

我所有的Python模块都应该显式导入相同的基本模块吗?

[英]Should all my Python modules be explicitly importing the same base modules?

For example: main.py: 例如:main.py:

import pygame
import mycolors
color1 = mycolors.blue

mycolors.py: mycolors.py:

import pygame
blue = pygame.Color(0, 0, 255)

My question specifically concerns the "import pygame" present in both files. 我的问题特别涉及两个文件中都存在的“ import pygame”。 Is it really necessary to import it within each module that requires it? 是否真的有必要在需要它的每个模块中导入它? (answer seem to be yes, it won't run without it.) Also, does this actually get imported twice? (答案似乎是肯定的,没有它就不会运行。)而且,这实际上是否被导入两次? does this have performance ramifications? 这会对性能产生影响吗?

The module is only imported once, so you don't have to worry about wasted resources. 该模块仅导入一次,因此您不必担心资源浪费。 You can see all the modules that have been imported anywhere in sys.modules . 您可以在sys.modules任何位置看到已导入的所有模块。 When the module is imported the second/third/etc. 导入模块时,第二/第三/等。 time you just get a reference to the module already in sys.modules 时间,您只是获得sys.modules已有模块的sys.modules

The reason you have to import it into both of the other modules is that it gets added to their namespace 您必须将其导入到其他两个模块中的原因是,它已添加到它们的名称空间中

This is very important in larger programs when there may be lots of modules with the same name, so you definitely wouldn't want a module to pop up in every other namespace whenever you imported it 当大型模块中可能有许多同名模块时,这是非常重要的,因此,绝对不要在导入模块时在其他每个命名空间中弹出该模块

I don't think these are the entire source files you're showing here. 我不认为这些是您在此处显示的全部源文件。 As they are now, import pygame is not necessary in main.py since you're not referencing it anywhere in that module. 就像现在一样,在main.py不需要import pygame ,因为您没有在该模块的任何地方引用它。

As for performance: It's not going to hurt perceptibly to import the same module several times. 至于性能:多次导入同一模块不会造成明显的伤害。 The "real" import (with the possible compilation step) happens only once. “实际”导入(可能的编译步骤)仅发生一次。

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

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