Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...