Reputation: 10055
I'm having some trouble with relative imports for the following situation.
I have a package, with two module directories, and I want to import a module from dir_b
to a module from dir_a
.
Here's an example of my package structure:
$ tree
.
├── builder
│ ├── build_moto.py
│ └── __init__.py
├── __init__.py
└── parts
├── car.py
├── __init__.py
├── moto.py
└── truck.py
I'm trying to import moto
inside build_moto
using relative imports, like this:
$ cat builder/build_moto.py
#!/usr/bin/python3
from .parts import moto
...but when I execute build_moto.py
, it generates the following error:
$ python3 builder/build_moto.py
Traceback (most recent call last):
File "builder/build_moto.py", line 3, in <module>
from .parts import moto
SystemError: Parent module '' not loaded, cannot perform relative import
I'd like to understand:
Upvotes: 0
Views: 65
Reputation: 7835
Often, this problem can be solved like this:
python3 -m builder.build_moto
The -m
argument means that you are running your module as part of a library:
-m mod : run library module as a script (terminates option list)
Upvotes: 1