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
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
Код: Выделить всё
$ cat >> driver.py
import project.one
$ python driver.py
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