Import Error on trying to import a submodule that imports a submodule

Viewed 8508

I feel like I'm missing something simple and basic. Here's a toy setup

PythonProject/
main.py
x/
    a.py
    y/
        b.py

b.py has a function foo with no dependencies

def foo():
    print("Hello World")

a.py needs foo from b.py to work and imports it directly

import y.b
def bar():
    #Do some stuff
    y.b.foo()

main.py needs bar from a.py

import x.a
x.a.bar()

Now, running a.py works just fine, it successfully imports b and finds foo. Trying to run main.py however breaks with an import error: specifically "import b" fails during "import a"

I get the impression that what needs to happen is that b needs to be exposed by an __init__.py in a/ but I'm unsure what the pythonic way of doing this would be.

What is the preferred solution to importing a module (a) which imports another module (b) preferably without bringing PythonProject awareness to a?

2 Answers

This was never properly answered even though Paul H alluded to the answer.

It's very simple and mentioned but not directly stated here.

If you have a directory like this:

sound/                      Top-level package
  __init__.py               Initialize the sound package
  formats/                  Subpackage for file format conversions
          __init__.py
          wavread.py
          wavwrite.py
          aiffread.py
          aiffwrite.py
          auread.py
          auwrite.py
          ...
  effects/                  Subpackage for sound effects
          __init__.py
          echo.py
          surround.py
          reverse.py
          ...
  filters/                  Subpackage for filters
          __init__.py
          equalizer.py
          vocoder.py
          karaoke.py
          ...

The __init__.py file in (for example "effects") needs to include

import effects.echo
import effects.surround
import effects.reverse

To call a submodule from within a submodule, as you asked, for example, echo calls surround, then you will need to import surround into echo using import effects.surround as surround

Related