6

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.

variable
  • 8,262
  • 9
  • 95
  • 215
Chirrut Imwe
  • 633
  • 10
  • 20

2 Answers2

9

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__":
svarog
  • 9,477
  • 4
  • 61
  • 77
JOHN_16
  • 616
  • 6
  • 12
1

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

Joe
  • 3,664
  • 25
  • 27