I can't make this work..
My structure is:
program_name/
__init__.py
setup.py
src/
__init__.py
Process/
__init__.py
thefile.py
tests/
__init__.py
thetest.py
thetest.py:
from ..src.Process.thefile.py import sth
Running: pytest ./tests/thetest.py
from program_name
gives :
ValueError: attempted relative import beyond top-level package
I tried also other approaches but i am receiving various errors.
But I would expect for the above to work.
Relative imports use dot(.) notation to specify a location. Single dot specifies that the module is in the current directory, two dots indicate that module is in its parent directory of the current location and three dots indicate that it is in grandparent directory and so on.
from __future__ import absolute_import means that if you import string , Python will always look for a top-level string module, rather than current_package.string . However, it does not affect the logic Python uses to decide what file is the string module.
Just solved a similar problem with a lot of googling. Here's two solutions without changing the existing file structor:
The way to import module from parent folder from ..src.Process.thefile.py import sth
is called "relative import".
It's only supported when launching as a package from the top-level package. In your case, that is launching command line from the directory which contains program_name/
and type (for win environment)
python -m program_name.tests.thetest
or simply (useful for many pytest files):
python -m pytest
Otherwise -- when trying to run a script alone or from a non top-level package -- you could manually add directory to the PYTHONPATH at run time.
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from src.Process.thefile import s
Try the first one first see if it's compatiable with the pytest framework. Otherwise the second one should always solve the problem.
Reference (How to fix "Attempted relative import in non-package" even with __init__.py)
When importing a file, Python only searches the current directory, the directory that the entry-point script is running from. you can use sys.path to include different locations
import sys
sys.path.insert(0, '/path/to/application/app/folder')
import thefile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With