Python - Import Module Error - Import .py file from another Parallel Folder in Visual Studio Code

While using Visual Studio Code, I encountered an issue where the   .py file from src folder cannot be found in the tests folder test case .py during runtime. When the test case file .py was run I, I was getting error Import Module Error - Startup not found. 

This is import Module Error is common when detecting and running files in a parallel folder in Visual Studio Code. It almost drove me nuts as the folder

Sharing this so that any developers using Python in Visual Studio Code will be spared the agony of trying to fix this 'import module error' issue. It is a nice IDE to use and I prefer it over Pycharm.


Steps to workaround


1) Add the init.py file to the folders 

You need a __init__.py for folder to be recognized as module


2) Add a Setup.py



At this point, I was  able to run the unit test from Conda prompt(with the environment activated of course)Unit tests are running. Great.

But for VS code, steps 1 and 2 are not enough. The tests were still failing and Import Module Error - Startup not found persisted


3) The workaround: Use sys.path.append() to add the parallel folder to the PATH

The issue is that the folder 'tests' is not in system path; to debug the issue, I ran the command print(sys.path) (On line 15) to view the path. And indeed, P:\XMLParser\src was not found

Only the tests folder and its parent folder were in the PATH. Read that this issue happens in VSCode. This should not happen in Pycharm.






Comments

Popular posts from this blog

Test Driven Development: How and Why

Using Git pre-commit hooks: Automated Testing of Code with Python Unit Tests

Five Things I Wish I Knew When Starting with Python