SyntaxStudy
Sign Up
Python Beginner 9 min read

Virtual Environments

Virtual Environments

A virtual environment is an isolated Python installation for a project. It keeps dependencies separate so different projects can use different library versions.

Creating a venv

# Create
python -m venv .venv

# Activate
# Windows:
.venv\Scripts\activate
# macOS/Linux:
source .venv/bin/activate

# Deactivate
deactivate

After Activation

# pip now installs into .venv only
pip install flask
pip install "sqlalchemy>=2.0"

# Save dependencies
pip freeze > requirements.txt

# Install on another machine
pip install -r requirements.txt

venv vs conda vs poetry

"""
venv:   Built-in, simple, lightweight
conda:  Manages Python itself + packages, great for data science
poetry: Modern dependency resolver + lock file + build tool
pipenv: Combines pip + virtualenv with Pipfile
"""

pyproject.toml (Modern)

[project]
name = "myapp"
version = "1.0.0"
requires-python = ">=3.10"
dependencies = [
    "flask>=3.0",
    "sqlalchemy>=2.0",
]

Best Practices

# Add to .gitignore:
.venv/
__pycache__/
*.pyc

# Always activate before working:
source .venv/bin/activate
Example
import sys, os

# Check if running inside a venv
in_venv = sys.prefix != sys.base_prefix
print("In virtual env:", in_venv)
print("Python path:", sys.executable)
print("Site packages:")
for path in sys.path:
    if "site-packages" in path:
        print(" ", path)
Pro Tip

Commit requirements.txt or pyproject.toml to version control, but NOT the .venv directory itself. Each developer recreates it with pip install -r requirements.txt.