buhtz
buhtz

Reputation: 12202

Run python project without relative imports

There is a lot written about how to structure the files and folders in a Python project. It is also written that relative imports should avoided. But I do not see how.

Here is an example project structure (imagine this as an upstream code repository).

Foo
├── foo
│   ├── bar.py
│   ├── __init__.py
│   └── __main__.py
└── run.sh

The __init__.py is empty and just indicates that foo is a package. I run the project with the run.sh script.

#!/usr/bin/env bash
python3 -m foo

This is my __main__.py showing the two approaches to import bar.py.

#!/usr/bin/env python3

# works
#from . import bar
# do not work
import bar

if __name__ == '__main__':
    bar.do()

The point is that only the first (currently out commented) works. When I use the second one I got this error message when running run.sh.

ImportError: No module named 'bar'

Upvotes: 4

Views: 42

Answers (1)

J_H
J_H

Reputation: 20540

Well, that's because there is no bar.

Rather, it is foo.bar.

When run in the context of foo, the . dot indicates foo, so .bar is foo.bar.

The solution in your MWE would be to modify the import line this way

from foo import bar

Upvotes: 2

Related Questions