0

This is the app structure.

app/
  setup.py
  package/
    __init__.py
    file.py 
  tests/
   tests.py
  ...

I'm trying to import from file.py into tests.py but it's throwing ValueError: Attempted relative import in non-package

Hence my question is how to import to a non-package from a package in python?

riser101
  • 610
  • 6
  • 23
  • Add an empty `conftest.py` in the `app` directory: `$ touch app/conftest.py` and import as usual: `from package import file`, `import package.file`, `from package.file import some_func` etc. – hoefling May 29 '18 at 11:43

3 Answers3

0

Use the below code in your tests.py

from ..package import file
0

You could use import_module from importlib in your tests.py:

from importlib import import_module

files = import_module("package.file")

Also available for python 2.7 as far as I have seen.

EDIT: This assumes that the top level structure 'app' is a package. i.e. has an __init__.py file

shmee
  • 4,721
  • 2
  • 18
  • 27
0

Or you can add the path to sys:

import sys
sys.path.append('/path/to/folder/')
import file
Christoffer
  • 528
  • 2
  • 15