0

Folder Structure:

  main
   |__ sub1
      |__ __init__.py
   |__ sub2
      |__ test.py

I need to import inside test.py:

from .. sub1 import SomeClass

It shows this error :

ValueError: attempted relative import beyond top-level package.

Thank you for responses.

Unhandled Exception
  • 2,906
  • 2
  • 9
  • 13
Jamshy
  • 23
  • 1
  • 6

2 Answers2

0

Neither main nor sub2 is a package because neither contains a __init__.py. See the relevant Python docs for more information.

Solomon Ucko
  • 2,682
  • 2
  • 14
  • 27
0

This is a special use case for testing from outside the main source folder. main has no reason to be a package, are there could be reasons for not to make it one.

IMHO, the best way is to start tests from the main directory. As the current directory is always in sys.path, sub1 will be directly importable and this would be enough:

from sub1 import SomeClass

But depending on your dev environment, you may need to launch tests directly from the test directory or any directory other than main. In that case, I am unsure that it is really a best practice, and I only use that for my tests, but a simple trick is to add the parent folder of the test folder to sys.path.

Here is what could be the beginning of test.py:

import os.path
import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from sub1 import SomeClass
...

Take it for what it is: a sys.path trick that just allows to access the main source folder from the test folder.

Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199