0

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:

  • why this configuration is not working?
  • what must be done in order to perform a relative import for this case in specific?
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
  • 1
    [**Relative imports for the billionth time**](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – martineau Oct 27 '17 at 23:12

1 Answers1

1

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)

erewok
  • 7,555
  • 3
  • 33
  • 45
  • Yes, that's a possible solution, but I need a different approach, like using relative imports. This example, is a representation of what I have from a part of a web application which I'm developing. – ivanleoncz Oct 27 '17 at 21:14
  • 1
    I don't understand. Perhaps you should consult the [canonical answer](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). – erewok Oct 27 '17 at 21:21
  • Thanks, @erewok :)! It helped me to understand a little bit more about my issue. – ivanleoncz Oct 28 '17 at 15:31