Virtual environments let you create isolated spaces for Python projects. Each project can have its own packages and versions without conflicts.
Why use virtual environments?
Different projects might need different versions of the same package.
Without isolation, installing packages globally can cause version conflicts.
Virtual environments solve this by keeping dependencies separate.
Creating a virtual environment
Python has a built-in module called venv.
Create one:
python -m venv myenv
This creates a folder called myenv with an isolated Python setup.
Common names: venv, .venv, or project-specific like myproject-env.
Activating the environment
Activate to use the isolated Python and packages.
On Windows:
myenv\Scripts\activate
On macOS/Linux:
source myenv/bin/activate
After activation, your terminal prompt usually changes (e.g., (myenv) appears).
Now python and pip refer to the isolated versions.
Installing packages
With the environment active:
pip install requests
pip install django
These packages install only inside the current environment.
Deactivating
Leave the environment:
deactivate
You return to the global Python setup.
Simple workflow example
# Create project folder and env
mkdir myproject
cd myproject
python -m venv venv
# Activate
source venv/bin/activate # or venv\Scripts\activate on Windows
# Install packages
pip install flask requests
# Work on project...
python app.py
# When done
deactivate
Checking installed packages
List packages in the current environment:
pip list
Save requirements for sharing:
pip freeze > requirements.txt
Install from requirements in a new environment:
pip install -r requirements.txt
Important notes
- Never commit the virtual environment folder to version control (it's large and system-specific).
- Always add it to
.gitignore. - Include
requirements.txtfor others to recreate the environment. - Use the same Python version for consistency.
Quick summary
- Create with
python -m venv name. - Activate with
source(macOS/Linux) orScripts\activate(Windows). - Install packages with
pipwhile activated. - Deactivate when finished.
- Use
requirements.txtto share dependencies.
Practice setting up a virtual environment for a small project. They are essential for clean and reproducible Python development.
Top comments (0)