ImportError: attempted relative import beyond top-level package. I am genuinely stuck

Viewed 242

Here is my file structure:
MainDir/
| Foo.py
| SubDir/
| |
| | Bar.py

Foo.py:

global var
var = 'value'
from SubDir import Bar

Bar.py:

from ..Foo import var
print(var)

With this code I am trying to get the value of var from Foo and get it in Bar.
I am getting this error while running Foo.py (and Bar.py): ImportError attempted relative import beyond top-level package

I know that there are multiple questions like this but I did not succeed to fix it by looking at all of them. I am stuck on this problem for about a week. Thanks in advance!

2 Answers

replace: from ..Foo import var by from Foo import var

those .. are trying to go beyond top package

\MainDir>dir /b/s

\MainDir\Foo.py
\MainDir\SubDir\Bar.py

enter image description here

Foo.py

global var
var = 'value'
from SubDir import Bar

Bar.py

from Foo import var
print(var)

Have you created proper Python packages with __init__.py? Additionally, you are likely to run into circular import errors if you are importing the same files into each-other.

I suggest avoiding relative imports and use absolute imports instead.

Related