[Python] Cannot Get Import to Work with Subpackages

Discussão em 'Python' iniciado por Stack, Novembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    The following structure (in Python 3.7) is not allowing me to import class A in module b:

    package:
    package:
    __init__.py
    a:
    __init__.py
    a.py
    b:
    __init__.py
    b.py


    The top-level __init__.py is blank. Here are the remaining files:

    a

    # package/package/a/__init__.py

    from .a import A


    # package/package/a/a.py

    class A:

    def __init__(self):
    pass


    b:

    # package/package/b/__init__.py

    from .b import B


    # package/package/b/b.py

    from package.a.a import A

    class B:

    def __init__(self):
    pass


    Without doing anything else, on Windows, if I try to run b.py (from within the b folder), I get the following error:

    ModuleNotFoundError: No module named 'package.a'


    If I add a main.py at the top level:

    package:
    package:
    __init__.py
    main.py
    a:
    __init__.py
    a.py
    b:
    __init__.py
    b.py


    containing

    # package/package/main.py

    import a
    import b


    and run main.py (from within package/package), I get the same error.

    If I change b.py to

    # package/package/b/b.py

    from ..a.a import A

    class B:

    def __init__(self):
    pass


    and run b.py (from within the b folder) or main.py (from within package/package), I get the error that

    ValueError: attempted relative import beyond top-level package


    The python docs make it seem like I should be able to do this though!

    Can someone please explain why I am getting these errors? I've seen a couple similar posts to this, but they haven't fixed my problem:

    1. Importing Submodules Python 3
    2. Python submodule importing correctly in python 3.7 but not 3.6

    Continue reading...

Compartilhe esta Página