4
votes

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?

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. - 9769953
I think 0 0 is right. I have a project that runs fine, but pylint gives this error too. - Pedro Queiroga

2 Answers

0
votes

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)
-4
votes

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

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