A virtual environment is a private, self-contained copy of Python for a single project, holding that project’s own interpreter and packages, separate from every other project on the machine.
Why Projects Are Kept Separate#
Python projects install packages, extra code written by others. Without a virtual environment, every package installs into one shared, system-wide Python. Two projects that need different versions of the same package then clash, because there is only one place for it to live.
A virtual environment gives each project its own space. Packages installed for one project stay with that project and do not affect any other. This keeps projects from interfering with each other and makes each one reproducible on another machine.
The .venv Folder#
Creating a virtual environment adds a folder to the project, usually named .venv. Inside it is a copy of the Python interpreter and a place for that project’s packages. Once VS Code is using the .venv interpreter, packages install into that folder rather than the system-wide Python.
project/
.venv/ the project's private interpreter and packages
main.py the project's codeThe .venv folder belongs to the project’s setup, not its source code. It is created once when the project is set up and does not need to be edited by hand.
⚠️ Mistakes
Installing packages without a virtual environment
Running pip install with no virtual environment active puts the package into the system-wide Python, where it is shared by every project and can clash with them. Create the virtual environment first, so packages install into the project’s own .venv.
Running against the wrong interpreter
A virtual environment only takes effect when its interpreter is the one being used. If VS Code has a different interpreter selected, the program runs outside the environment and the project’s packages appear to be missing. Make sure the interpreter shown in the status bar is the one inside .venv.
Committing the .venv folder
The .venv folder can be recreated at any time from the project’s package list, so it does not belong in version control. Sharing the code plus the list of packages is enough for someone else to rebuild the environment.
📚 Resources
- Python Virtual Environments (external link), Python.org
- Python environments in VS Code (external link), official guide