tags:

views:

23

answers:

1

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.

A: 

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!

Alex Martelli
Thanks for the answer. Do you know where can I find more information about the "side effect"? I did some google search but couldn't get any useful result.
sayap
general (dated but still good and clear) tutorial on importing at http://effbot.org/zone/import-confusion.htm (doesn't cover packages and `__init__.py`), the official tutorial at http://docs.python.org/tutorial/modules.html does.
Alex Martelli