Search code examples
pythonimporterror

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


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!


Solution

  • 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)