开发者

python package get imported automatically when importing a global from a module

开发者 https://www.devze.com 2023-01-11 16:41 出处:网络
Let\'s say I have these files: - package1/ - __init__.py - package2/ - __init__.py - module1.py Content of package1/__init__.py:

Let's say I have these files:

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

Content of package1/__init__.py:

from package2.module1 import var1
print package2

Empty package1/package2/__init__.py

Content of package1/package2/开发者_如何转开发module1.py:

var1 = 123

The question is why would package2 get imported? Running pylint against package1/__init__.py will actually give error Undefined variable 'package2', but the code works.


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).

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).

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. This gives you the chance to do all needed checks and initializations, of course!

0

精彩评论

暂无评论...
验证码 换一张
取 消