What is the priority of importing a name, submodule or subpackage from a package in python 2.7?

The official Python 2 tutorial says:

Note that when used from a_package import a_item, an element can be either a submodule (or subpackages) of a package, or some other name defined in the package, for example, a function, class or variable.

Then what if a_package has a a_package 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 , but I'm not sure if this is the canonical order, which in all cases should use the python import functions.

+5
source share
1 answer

The following sentence, after you indicate in your question, confirms that the names defined in the package ("variables" to use your wording) take precedence over submodules / packages:

The import statement first checks to see if an item is defined in the package; if not, it assumes that it is a module and tries to load it.

I cannot find explicit confirmation in the document for Python 2.7 that packages take precedence over modules. I found this in PEP 420 :

During import processing, the import engine will continue to iterate over each directory in the parent path, as it does in Python 3.2. When searching for a module or package named "foo" for each directory in the parent path:

  • If <directory>/foo/__init__.py , the regular package will be imported and returned.
  • If not, but <directory>/foo.{py,pyc,so,pyd} found, the module is imported and returned.

... which, although it only explicitly states that this behavior is in Python 3.2, one might assume that "... and previous versions of Python." Again, this confirms your view 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 this probably does not go far beyond the core Python developers; in every sense and purpose it is undocumented and can cause extremely difficult to track errors.

+8
source

Source: https://habr.com/ru/post/1203452/


All Articles