Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I got an error Attempted relative import beyond top-level package

I am writing a python application and trying to manage the code in a structure.

The directory structure that I have is something like the following:-

package/
   A/
     __init__.py
     base.py
   B/
     __init__.py
     base.py
app.py
__init__.py

so I have a line in A/init.py that says

from .base import *

No problem there, but when I put the same line in B/init.py

from .base import *

I get an error

E0402: Attempted relative import beyond top-level package.

Isn't the two supposed to be identical? what exactly am I doing wrong here?

I am using Python 3.6, the way I ran the application is from the terminal with

> python app.py

Thanks

UPDATE: Sorry, The error is from somewhere else.

In A/base.py i have

class ClassA():
  ...

In B/base.py I have

from ..A import ClassA

class ClassB(ClassA):
  ...

The error came from the import statement in B/base.py

from ..A import ClassA

UPDATE #2 @JOHN_16 app.py is as follows:-

from A import ClassA
from B import ClassB

if __name__ == "__main__":
  ...

Also updated directory to include empty init.py as suggested.

like image 827
Chirrut Imwe Avatar asked Apr 23 '18 12:04

Chirrut Imwe


People also ask

What is top level package in Python?

“Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.

What is a relative import?

A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit.

How do you use relative import in Python?

Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.


2 Answers

This is occurred because you have two packages: A and B. Package B can't get access to content of package A via relative import because it cant move outside top-level package. In you case both packages are top-level.

You need reorganize you project, for example like that

.
├── TL
│   ├── A
│   │   ├── __init__.py
│   │   └── base.py
│   ├── B
│   │   ├── __init__.py
│   │   └── base.py
│   └── __init__.py
└── app.py

and change content pf you app.py to use package TL:

from TL.A import ClassA
from TL.B import ClassB

if __name__ == "__main__":
like image 129
JOHN_16 Avatar answered Oct 02 '22 11:10

JOHN_16


My problem was forgetting __init__.py in my top level directory. This allowed me to use relative imports for folders in that directory.

like image 42
Joe Avatar answered Oct 02 '22 11:10

Joe