Python – VSCode 1.39.x & Python 3.7.x: “ImportError: attempted relative import with no known parent package” – when started without debugging (CTRL+F5))

importpackagepythonpython-unittestvisual-studio-code

  • when running Python test from withing VS Code using CTRL+F5 I'm getting error message

    ImportError: attempted relative import with no known parent package

Error message text: "ImportError: attempted relative import with no known parent package"

  • when running Python test from VS Code terminal by using command line

    python test_HelloWorld.py

    I'm getting error message

    ValueError: attempted relative import beyong top-level package

Error Message: "ValueError: attempted relative import beyond top-level package"

Here is the project structure

Project structure

How to solve the subject issue(s) with minimal (code/project structure) change efforts?

TIA!

[Update]

I have got the following solution using sys.path correction:

The subject issue solution using sys.path correction

import sys
from pathlib import Path
sys.path[0] = str(Path(sys.path[0]).parent)

but I guess there still could be a more effective solution without source code corrections by using some (VS Code) settings or Python running context/environment settings (files)?

Best Answer

You're bumping into two issues. One is you're running your test file from within the directory it's written, and so Python doesn't know what .. represents. There are a couple of ways to fix this.

One is to take the solution that @lesiak proposed by changing the import to from solutions import helloWorldPackage but to execute your tests by running python tests/test_helloWorld.py. That will make sure that your project's top-level is in Python's search path and so it will see solutions.

The other solution is to open your project in VS Code one directory higher (whatever directory that contains solutions and tests). You will still need to change how you execute your code, though, so you are doing it from the top-level as I suggested above.

Even better would be to either run your code using python -m tests.test_helloWorld, use the Python extension's Run command, or use the extension's Test Explorer. All of those options should help you with how to run your code (you will still need to either change the import or open the higher directory in VS Code).

Related Topic