A virtual environment is a tool that creates isolated Python environments on your system. It allows you to manage dependencies for multiple projects independently, avoiding conflicts between them.
For example, you might need different versions of the same library for two separate projects, and virtual environments ensure they don't interfere with each other.
Why Use Virtual Environments?
- Avoid conflicts: Different projects can use different versions of the same library.
- Keep projects self-contained: Each project has its own dependencies, separate from global Python.
- Easier collaboration: Share
requirements.txt
so others can recreate the exact same environment. - Safe experimentation: Try new libraries or upgrades without breaking your global setup.
Creating a Virtual Environment
You can create a virtual environment using Python's built-in venv
module.
Steps:
- Create the Environment:
python -m venv myenv
This creates a directory named myenv
containing the virtual environment.
- Activate the Virtual Environment:
-
Linux/macOS:
source myenv/bin/activate
-
Windows (Command Prompt):
myenv\Scripts\activate.bat
-
Windows (PowerShell):
myenv\Scripts\activate.ps1
- Deactivate the Environment:
deactivate
Installing Dependencies
Once the virtual environment is activated, any packages installed via pip
will only apply to that environment. These packages won’t affect the global Python environment or other virtual environments.
pip install <package-name>
You can also freeze the environment to share dependencies:
pip freeze > requirements.txt
And later recreate it with:
pip install -r requirements.txt
Best Practices
- Always create a virtual environment for each project to avoid dependency issues.
- Use
requirements.txt
(orpyproject.toml
for modern setups) to track dependencies. - Avoid installing packages globally, keep your global Python clean.
- Name environments clearly (e.g., venv, .venv, or project-env).
- Deactivate when done working on a project to avoid confusion.