Python - import order for modules

For example, there is a folder:

.
├── file_a.py
├── file_b
│   └── __init__.py
└── file_b.py

where it file_a.pyhas something like:

from file_b import some_function

I know this is definitely not good practice, but what is the resolution order?

i.e. How does python decide which module to import for "absolute import"?

+4
source share
3 answers

I'm not sure where (or there is) this information is contained in the documentation - a quick check in the import of system documents didn't include it - but PEP 420 says the following:

When searching for a module or package named "foo" for each directory in the parent path:

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

, .

, PEP 420, , .

+4

@JonKiparsky, importlib , , importlib._bootstrap.FileFinder.find_spec, , . , @user2357112 , , , .

+2

Did a little experiment by doing somelib.pyand somelib/__init__.py then tried the following

>>> from somelib import foo
in somelib/__init__.py
>>>

Obviously python prefers directory-based file-based module

As @scnerd points out, this may be random behavior, but this is what I see in the default implementation.

If you want to know how this happens, you should probably look through importlib for horrible details.

+1
source

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


All Articles