Skip to content
Advertisement

Python ImportError and ValueError in VSCode/pytest

This is what my project looks like (oversimplified):

root/
├── test/
|   └── test_code.py
└── code.py

Whenever I run pytest standing in root/ I get ImportError : Attempted relative import with no known parent package.

If I move test_code.py out to root/ everything works fine. But this is not an option since I have many modules and that is why I need to put ALL test modules inside a test-folder for organizing.

I am using VSCode and the weird thing is: VSCode finds my imported functions inside test_code.py.

from ..code import func – if I right-click on func VSCode jumps up to code.py outside of test-folder.

When I try to run test_code.py directly in VSCode I get ValueError: attempted relative import beyond top-level package.

How can VSCode find my imported functions but cannot run them and pytest cannot run them either?

  • I have tried adding __init__.py to make root/ a package.
  • I have tried adding .env as stated here.

Solution

  1. I moved code.pyinto src/ and added __init__.py files in each folder to let Python know that test/ and src/ are packages:
root/
├── test/
|   ├── __init__.py
|   └── test_code.py
└── src/
    ├── __init__.py
    └── code.py
  1. I had to use absolute imports in all files: from folder.file import function. Read about absolute vs. relative imports here. If you open your code in root – VSCode will now find your imports!

This is what test_code.py looks like:

from src.code import func

Finally, running pytest works! If you want to run code.py from terminal you have to run: $ python3 -m src.code

Advertisement

Answer

Solution

  1. I moved code.pyinto src/ and added __init__.py files in each folder to let Python know that test/ and src/ are packages:
root/
├── test/
|   ├── __init__.py
|   └── test_code.py
└── src/
    ├── __init__.py
    └── code.py
  1. I had to use absolute imports in all files: from folder.file import function. Read about absolute vs. relative imports here. If you open your code in root – VSCode will now find your imports!

This is what test_code.py looks like:

from src.code import func

Finally, running pytest works! If you want to run code.py from terminal you have to run: $ python3 -m src.code

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement