Python import module from imported module issue

  python

I have a project structure like that:

main.py
src
  foo.py
  bar.py

And I am trying to import foo.py from main.py.

# main.py
import src.foo

# I also tried
# from src import foo
# or
# from src.foo import *

But foo.py imports bar.py.

# foo.py
import bar

# also tried
# from bar import *

But it has ModuleNotFoundError.

ModuleNotFoundError: No module named 'bar'

It worked when I did in foo.py something like this:

import src.bar

But I don’t want to do that every time I import something. Why can’t the imported module use its own parent directory and how can I fix it?

Source: Python Questions

LEAVE A COMMENT