7

I'm using python 3.7 and ran into a relative import error "Attempted relative import beyond top-level package" with the following folder structure:

├── app
│   ├── __init__.py
│   ├── services
│   │   └── item_service.py
│   └── views
│       ├── home.py
│       ├── __init__.py

My goal: import variable foo from the top level _init_.py to item_service.py using

from .. import foo

Pylint gives the error when trying this.

However the same exact import statement works in home.py, and if I add a empty _init_.py file to the services folder, the import works.

So my my question is, why? Does python require your module to be in a subpackage in order to relatively import parent package's contents?

4
  • 3
    Possible duplicate of stackoverflow.com/questions/30669474/… Commented Jul 8, 2019 at 13:58
  • 2
    Possible duplicate of beyond top level package error in relative import Commented Jul 8, 2019 at 13:59
  • 2
    Pylint may parse your code inside the package, while it should stay below the app level. If it's only pylint, I'd ignore it for now. Commented Jul 8, 2019 at 13:59
  • I think 0 0 is right. I have a project that runs fine, but pylint gives this error too. Commented May 6, 2020 at 17:15

2 Answers 2

-1

For me it got resolved in following ways:

  1. First import the directory (import dir)
  2. Then try to import the views/class (from dir import views/class)
Sign up to request clarification or add additional context in comments.

Comments

-5

To solve: Add init.py to all directories involved.

Add sys.path.append("..") BEFORE importing from sibling directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.