Yarden Akin
Yarden Akin

Reputation: 81

How to import a module in a subdirectory that imports another module in that same subdirectory?

In a module that I import, I'm trying to import another module, that is located in that same directory.

My files look something like this...

project
├── main.py
└── app
    └── foo.py
    └── bar.py

main.py

import app.foo as Foo

foo.py

import bar

So now, when I run main.py, I get a

ModuleNotFoundError: No module named 'bar'

There are so many similar questions, but none of them seem to be my exact situation.

How can I get this to work?

Upvotes: 3

Views: 623

Answers (2)

Hou Lu
Hou Lu

Reputation: 3222

This is mainly because when run main.py directly, Python would use the directory where main.py locates as the current running directory, thus when you import bar directly in foo.py, Python interpreter will try to find bar module in that running directory, where bar.py doesn't exist apparently. That is the reason why relative import is needed, as answered by @Robert Szczelina.
If you run foo.py directly, the sentense import bar will be right.

Upvotes: 0

Robert Szczelina
Robert Szczelina

Reputation: 63

Imports from .. or . should work:

from . import bar 

remember to add __init__.py (empty file) inside app directory.

Edit: it could be done only if using foo and bar as modules. E.g. you would not be able to run "python foo.py" or "python foo.bar". Outside of app directory, you could try the code with:

python -m app.foo

(mind the lack of .py extension)

Upvotes: 4

Related Questions