Thursday, 5 October 2017

Python 3 module import error from another folder




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.


Answer




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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...