A virtual environment in Python is an isolated workspace where you can install packages and run projects without affecting the system-wide Python installation. Each project can have its own dependencies, versions, and configuration. This avoids conflicts between projects and ensures long-term stability.
Virtual environments are essential for professional development because real applications often require specific versions of libraries. Using venv makes a project self-contained, reproducible, and easier to maintain.
A virtual environment is a dedicated folder that contains:
This isolation ensures that:
Without virtual environments, global installations can quickly become unmanageable, especially when multiple projects require different versions of the same library.
Real-world Python applications commonly depend on libraries like Flask, Django, NumPy, Pandas, or TensorFlow. These libraries release frequent updates. One project may rely on an older version, while another may require the latest.
Using venv solves these issues by allowing each project to maintain its own set of packages.
Python provides the built-in venv module to create a virtual environment.
python -m venv myenv
This creates a directory named myenv containing:
No output appears if the command succeeds.
Activation switches your terminal to use the environment’s Python instead of the system Python.
myenv\Scripts\activate
source myenv/bin/activate
Your terminal prompt changes to:
(myenv) C:\Users\User>
This indicates the environment is active.
All pip install commands now install packages into myenv, not globally.
To exit the virtual environment:
deactivate
The environment name disappears from the terminal prompt.
Once activated, you can install packages normally using pip.
pip install flask
pip list
Flask 2.3.0
pip 23.2
setuptools 65.0
All packages exist inside the environment’s folder.
A virtual environment works best when you save a list of packages required for your project. This allows other developers or servers to recreate the same environment.
pip freeze > requirements.txt
pip install -r requirements.txt
This ensures complete environment replication.
Virtual environments are self-contained. To delete one, simply remove the folder.
rm -r myenv
or on Windows:
rmdir /s /q myenv
No special deactivation or cleanup is required.
Most developers use VS Code with venv.
Steps:
VS Code will now use the virtual environment’s Python and packages.