Search code examples
pythonrelative-import

python 3.9 Package Relative Imports not working


I am setting up a sample python package using the "Package Relative Imports" syntax, referring to this document. And it is not working, the Relative Imports in b.py ran into problems. Here are my file structure (all __init.py__ are empty)

lib/
    dir1/
        __init.py__
        a.py
    dir2/
        __init.py__
        b.py
    __init.py__
    c.py

File a.py

def a_foo(a, b):
    return a + b

File b.py

from ..dir1.a import a_foo
def b_bar():
    return a_foo(1,2)

File c.py

from dir2.b import b_bar
print(b_bar())

I ran c.py and got the following error

PS D:\tmp\py> python c.py  
Traceback (most recent call last):
  File "D:\tmp\py\c.py", line 1, in <module>
    from dir2.b import b_bar
  File "D:\tmp\py\dir2\b.py", line 1, in <module>
    from ..dir1.a import a_foo
ImportError: attempted relative import beyond top-level package

I think I structured everything according to the document. Not sure why the relative import is not working. I have a Python 3.9.7 running in Windows 10.


Solution

  • I think your from dir2.b is being interpreted as an absolute import, not relative. The docs you refer to say:

    Try:

    from .dir2.b import b_bar
    

    Note the preceding period. It means look in the current directory for "dir2"

    Then call it using

    python -c "import lib.c"