Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to make paths work - attempted relative import beyond top-level package

Tags:

python

pytest

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.

like image 403
George Avatar asked Mar 09 '17 07:03

George


People also ask

How do you use relative import in Python?

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.

What is Absolute_import?

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.


2 Answers

Just solved a similar problem with a lot of googling. Here's two solutions without changing the existing file structor:

1

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

2

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)

like image 177
Yibo Avatar answered Sep 25 '22 05:09

Yibo


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
like image 39
kishlaya kumar Avatar answered Sep 23 '22 05:09

kishlaya kumar