Home > Mobile >  How do you import a module that imports another module in a subfolder?
How do you import a module that imports another module in a subfolder?

Time:12-10

So this is my folder structure:

root
  module_a
    hello.py
    submodule_a
      hi.py
  module_b
    howdy.py

hello.py calls a method in hi.py. howdy.py calls a method in hello.py

This is the content of each file:

hi.py

def myhi(hi):
    print("myhi "   hi)

hello.py

from submodule_a.hi import myhi

def myhello(hello):
    myhi("myhello "   hello)

howdy.py

from module_a.hello import myhello

def myhowdy(howdy):
    myhello("myhowdy "   howdy)

So the first issue is that howdy.py cannot find module_a, so I did sys.path.append(".") inside howdy.py.

But now the new problem is that, from howdy.py, it cannot find submodule_a from hello.py.

How do you solve this issue? Is it possible to solve it without editing hello.py at all?

I've tried messing with __init__.py but I couldn't find anything that could solve the second problem.

CodePudding user response:

The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .

CodePudding user response:

create a __init__.py file in module_a and module_b and submodule_a then import the functions you want to use in another directory like these:

module_a/__init__.py

from hello import myhello
from submodule_a import myhi

module_a/submodule_a/__init__.py

from hi import myhi

module_b/__init__.py

from howdy import myhowdy
  • Related