2

I am trying to reuse a package that I have written in a new project and I am currently having problems with imports. I recreated a minimal example that shows the problem. The folder structure is as following:

test\
    __init__.py
    main.py
    package\
        __init__.py
        p1.py
        p2.py

The problem stems from the fact that p1 imports p2

from __future__ import print_function
print("P1",__name__,__package__)

import p2

def a():
    p2.b()
    print("A")

if __name__=="__main__":
    a()
    p2.b()

And this is the main.py code:

from __future__ import print_function
print("MAIN",__name__,__package__)
from package.p1 import a
from package.p2 import b

if __name__=="__main__":
    a()
    b()

and here is p2.py:

from __future__ import print_function
print("P2",__name__,__package__)

def b():
    print("B")

if __name__=="__main__":
    b()

When running main.py I get a ImportError: No module named p2

I can fix this according to the modules documentation by changing the import in p1:

Since the name of the main module is always "main", modules intended for use as the main module of a Python application should always use absolute imports.

My understanding of this sentence is that I should change the import in p1 to from package import p2. However this breaks p1:

ImportError: No module named package

I've found other answers that just suggest to modify sys.path explicitly adding folders but that does not seem clean to me. What am I missing? What is the pythonic way to do this?

igon
  • 3,016
  • 1
  • 22
  • 37

0 Answers0