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?

Ozame
  • 89
  • 2
  • 5
  • 3
    Possible duplicate of https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import – Emre Sevinç Jul 08 '19 at 13:58
  • 2
    Possible duplicate of [beyond top level package error in relative import](https://stackoverflow.com/questions/30669474/beyond-top-level-package-error-in-relative-import) – Green Cloak Guy Jul 08 '19 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. – 9769953 Jul 08 '19 at 13:59
  • I think 0 0 is right. I have a project that runs fine, but pylint gives this error too. – Pedro Queiroga May 06 '20 at 17:15

2 Answers2

-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)
Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35
-5

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

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

Adel
  • 161
  • 6