简体   繁体   English

从模块导入全局时自动导入python包

[英]python package get imported automatically when importing a global from a module

Let's say I have these files: 假设我有这些文件:

- package1/
  - __init__.py
  - package2/
    - __init__.py
    - module1.py

Content of package1/__init__.py : package1/__init__.py

from package2.module1 import var1
print package2

Empty package1/package2/__init__.py 清空package1/package2/__init__.py

Content of package1/package2/module1.py : package1/package2/module1.py

var1 = 123

The question is why would package2 get imported? 问题是为什么package2会被导入? Running pylint against package1/__init__.py will actually give error Undefined variable 'package2' , but the code works. 针对package1/__init__.py运行pylint实际上会给出错误的未定义变量'package2' ,但代码可以工作。

When you import a module from within a package the package is always imported (loaded, if it's not already in sys.modules ) first -- which may have the side effect of binding the package's name in the importing module, though that's not guaranteed (depends on the Python implementation and version). 当您从包中导入模块时,首先会导入包(如果它尚未在sys.modules ,则加载) - 这可能会导致在导入模块中绑定包名称的副作用,但这并不能保证(取决于Python实现和版本)。

And, importing something "from inside a module" (a practice I personally abhor, but that's another issue) must also ensure the module is loaded (if it's already in sys.modules it doesn't of course need to be loaded again, but if it isn't, it must get loaded and put in sys.modules ). 并且,从模块内部导入一些东西(我个人厌恶的做法,但这是另一个问题)还必须确保模块已加载(如果它已经在sys.modules它当然不需要再次加载,但是如果不是,则必须加载并放入sys.modules )。

Both of these behaviors (the guaranteed parts;-) are all about the "integrity" of packages and modules: when you write a module you can be sure that, even if somebody misguidedly tries to pick and choose which bits to import, they'll be affecting only the name bindings in their own module, but your module will always get loaded as a whole . 这两种行为(保证部分;-)都是关于包和模块的“完整性”:当你编写一个模块时,你可以确定 ,即使有人错误地试图选择要导入哪些位,它们也是'将只影响他们自己的模块中的名称绑定,但您的模块将始终作为一个整体加载。 And similarly for somebody importing a module from within your package (a perfectly OK practice, BTW): you know your package's __init__.py will get loaded first, before anything happens. 类似地,有人从你的软件包中导入一个模块(一个非常好的做法,BTW):你知道你的软件包的__init__.py将在任何事情发生之前首先被加载。 This gives you the chance to do all needed checks and initializations, of course! 当然,这使您有机会进行所有必要的检查和初始化!

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

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