In the official Python 2 tutorial it says:
Note that when using from a_package import an_item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable.
Then what if a_package
has a subpackage named an_item
, a variable named an_item
and a module named an_item
at the same time? What is the priority? I did an experiment and the result shows priority as variable
> subpackage
> submodule
, yet I am not sure if it is the canonical order the python import functionality follows in all cases.
The next sentence after the one you quote in your question confirms that names defined within a package ("variables", to use your wording) take precedence over submodules/packages:
The
import
statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it.
I can't find an explicit confirmation in the documention for Python 2.7 that packages take precedence over modules. I did find this, in PEP 420:
During import processing, the import machinery will continue to iterate over each directory in the parent path as it does in Python 3.2. While looking for a module or package named "foo", for each directory in the parent path:
- If
<directory>/foo/__init__.py
is found, a regular package is imported and returned.- If not, but
<directory>/foo.{py,pyc,so,pyd}
is found, a module is imported and returned.
... which, while it only explicitly states that this is the behaviour in Python 3.2, could be taken to imply "... and previous versions of Python". Again, this confirms your finding that packages take precedence over modules.
However: it would be a terrible idea to rely on this implementation detail. The number of people in the world who are aware of it probably doesn't extend far beyond Python's core developers; it is to all intents and purposes undocumented, and is liable to cause extremely hard-to-track down bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With