0 votes
1 view
in Python by (47.8k points)

Imagine this directory structure:

app/

  __init__.py

  sub1/

    __init__.py

    mod1.py

  sub2/

    __init__.py

    mod2.py

I'm coding mod1, and I need to import something from mod2. How should I do it?

I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".

I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?

1 Answer

0 votes
by (107k points)

The main problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.

So you can use the following piece of code to overcome your problem:-

main.py

Setup.py

app/ ->

    __init__.py

   package_a/ ->

      __init__.py

      module_a.py

  package_b/ ->

      __init__.py

      module_b.py

Explanation of the code:-

You will run python main.py so this main.py  imports app.package_a.module_a and the module_a.py file imports app.package_b.module_b.

Related questions

0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...