Home > Back-end >  Is there a possibility to add a project reference for python in vscode?
Is there a possibility to add a project reference for python in vscode?

Time:03-16

With C# projects, there is an easy way to reference other projects inside a solution. Now, I would like to know, if there is a similar way in python projects.

Lets say, I have a folder structure like this:

Base_directory/Project/SomeFile.py
Base_directory/Project_UnitTests/SomeFileTests.py

SomeFile.py

class SomeClass:
    pass

For the unit tests, it works fine, if I use relative imports. SomeFileTests.py:

from ..Project.SomeFile import SomeClass
#...    

But, what I would like to achieve is to have the following code:

from Project.SomeFile import SomeClass
#...

But for this, I obviously need a reference to the Project folder. I know, I could work with the python-path variable directly inside the code, but then I would need to have the path to that folder inside the unit test code - and I do not think, it belongs there.

Is there an elegant way to add project references in Visual Studio Code using Python?

CodePudding user response:

You can modify PYTHONPATH through terminal.integrated.env.* and/or within an .env file. You can refer to official docs here.

The PYTHONPATH environment variable specifies additional locations where the Python interpreter should look for modules. In VS Code, PYTHONPATH can be set through the terminal settings (terminal.integrated.env.*) and/or within an .env file.

But they are some different:

When the terminal settings are used, PYTHONPATH affects any tools that are run within the terminal by a user, as well as any action the extension performs for a user that is routed through the terminal such as debugging. However, in this case when the extension is performing an action that isn't routed through the terminal, such as the use of a linter or formatter, then this setting will not have an effect on module look-up.

When PYTHONPATH is set using an .env file, it will affect anything the extension does on your behalf and actions performed by the debugger, but it will not affect tools run in the terminal.

If needed, you can set PYTHONPATH using both methods.

Exactly meet your target:

An example of when to use PYTHONPATH would be if you have source code in a src folder and tests in a tests folder. When running tests, however, those tests can't normally access modules in src unless you hard-code relative paths.

To solve this problem, you could add the path to src to PYTHONPATH by creating an .env file within your VS Code workspace.

PYTHONPATH=src

Then set python.envFile in your settings.json file to point to the .env file you just created. For example, if the .env file was in your workspace root, your settings.json would be set as shown:

"python.envFile": "${workspaceFolder}/.env"

  • Related