0

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?

One Nose
  • 52
  • 1
  • 7

1 Answers1

0

Your (sane) options are:

import src.bar      # Absolute import

or

from . import bar   # Relative import

import bar doesn't work in Python 3 because it has fundamental problems. Imagine a tree like:

spam\
  math.py
  eggs.py

If eggs.py needs the built-in math module, and does import math, on Python 2, it doesn't get the built-in, it gets spam.math. And it has no reasonable way of getting the built-in math at all (aside from a __future__ import that gives you Python 3-style absolute imports).

from . import bar 

is the way to reference a sibling module without explicitly naming the parent package. Use it.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Insane options include modifying `sys.path` so your own directory is part of it; it's not a sane option though, as it could lead to a given module getting imported twice independently, as it would be visible under both `src.bar` and `bar`. – ShadowRanger Nov 24 '20 at 05:26
  • Thanks. So basically you're saying I can't do that. – One Nose Nov 24 '20 at 05:34
  • 1
    @OneNose: I'm saying `from . import bar` is correct, and does what you requested. Other solutions start at bad, and get worse. The only way `import bar` works is if you downgrade to Python 2, which I don't recommend for multiple reasons, starting with it being end of lifed nearly a year ago. – ShadowRanger Nov 24 '20 at 05:37