pythonimporterrorrelative-import

ImportError: attempted relative import beyond top-level package


I have a folder like this:

draft
    model
        a.py
    package
        b.py

I want to import a function inside a.py into b.py by this code from ..model import a.
But I got an error like this:
ImportError: attempted relative import with no known parent package

I try the first answer of this question
python -m package.b
But another error occur:
ImportError: attempted relative import beyond top-level package

I have try to add __init__.py to both model and package, and draft folder, too.
But the same error still happened.

I know that there's a solution like:

import sys
sys.path.append(f'{source_path}/draft/model')

But when i move this code to another computer, the source_path must be changed. It may occur error when i forget.

Can anyone help me ?


Solution

  • When you run "python -m package.b", the working directory is "/draft" with "model" and "package" being two separate ROOT packages in it. Note these two packages don't share a common parent package so that from .. doesn't work.

    If you insist on using relative imports, place the files in a common parent folder as root package. For example, rearrange your directory structure as:

    draft
        project
            model
                a.py
            package
                b.py
    

    and run with command:

    python -m project.package.b