Почему относительный импорт не работает без предварительного импорта пакета как модуляPython

Программы на Python
Гость
Почему относительный импорт не работает без предварительного импорта пакета как модуля

Сообщение Гость »


I'm experiment with relative imports and have found very interesting case here:

Код: Выделить всё

$ mkdir project
$ cat >> project/one.py
from . import two
$ touch project/two.py
$ python project/one.py
Traceback (most recent call last):
File "project/one.py", line 1, in 
from . import two
ImportError: attempted relative import with no known parent package
The author explains that

You must ensure that the pkg package is imported before its contents can do relative imports of each other. There are many ways to do this, but in general you want a program to start with a single absolute import first.

And shows the following solution:
The simplest thing is to run the script as a module, using the package name rather than the source code file name. So this runs without error:

Код: Выделить всё

$ python -m project.one
Practically speaking, if we want an “entry point” to the code, we should use a driver script that is outside the package, which can find the package by absolute import and use something from it:

Код: Выделить всё

$ cat >> driver.py
import project.one
$ python driver.py
That worked because the containing folder for driver.py was on the module search path (sys.path), because of how we started Python - so the project folder could be found directly within the CWD.

Could somebody elaborate on the requirement to first import a package as a module to enable relative imports inside this package? Where is it defined in the spec (link would be good)?
Thanks


Источник: https://stackoverflow.com/questions/781 ... s-a-module

Вернуться в «Python»