2

My apps are organized like this:

apps/
    code/
        libglobal/
            funglobal.py
    tests/
        project/
            liblocal/
                funlocal.py
            main.py

In main.py I have:

import liblocal.funlocal

In funlocal.py I try to import funglobal.py with:

from ....code.libglobal import funglobal

When I run

python3 -B tests/project/main.py

I get an error:

from ....code.libglobal import funglobal
ValueError: attempted relative import beyond top-level package

I have read a lot of information about relative imports with python3 and still don't find how to solve this error without changing the apps organization radically. Any solution?

Medical physicist
  • 2,510
  • 4
  • 34
  • 51

2 Answers2

2

As the script being executed has its __name__ set as __main__ and defines itself to be on the top level of the package, it refuses to recognize scripts in sibling directories.

You can fix this with a sys.path hack:

import sys, os
sys.path.insert(0, os.path.abspath('../..'))

or an interseting alternative with setuptools is presented in this answer.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
0

Have you a __init__.py script in each folder ?

If no, you should create an empty script named __init__.py in each folder.