Web Analytics

Virtual Environments

Advanced ~20 min read

Virtual environments are isolated Python environments that allow each project to have its own set of dependencies without conflicts. Using venv, you can create separate environments for different projects, ensuring that package versions don't interfere with each other. This is essential for professional Python development!

Why Virtual Environments?

Without virtual environments, all Python packages are installed globally. This causes problems when different projects need different versions of the same package. Virtual environments solve this by giving each project its own isolated Python environment with its own packages.

Output
Click Run to execute your code
Benefits of Virtual Environments:
- Isolation: Each project has its own packages, no conflicts
- Reproducibility: Easy to recreate exact environment with requirements.txt
- Clean System: Keep your system Python installation clean
- Version Control: Track dependencies per project
- Deployment: Match production environment exactly

Creating Virtual Environments

Python 3.3+ includes the venv module for creating virtual environments. The command creates a new directory containing a Python interpreter and a copy of the standard library.

Output
Click Run to execute your code

Activating Virtual Environments

After creating a virtual environment, you must activate it before use. Activation modifies your PATH so that Python and pip commands use the virtual environment's versions. The command differs between operating systems.

Output
Click Run to execute your code
Pro Tip: When activated, your terminal prompt shows the environment name in parentheses, like (myenv). This confirms the virtual environment is active. You can have multiple terminals with different environments activated simultaneously!

Working with requirements.txt

The requirements.txt file is the standard way to specify project dependencies. You can generate it from your current environment and use it to recreate the exact same environment elsewhere.

Output
Click Run to execute your code
Important: Always include requirements.txt in your version control (git)! This allows others (and you on different machines) to recreate the exact environment. Never commit the virtual environment directory itself - it's large and OS-specific!

Common Mistakes

1. Not activating the virtual environment

# Wrong - installing globally
python -m venv myenv
pip install requests  # Installs to system Python, not venv!

# Correct - activate first
python -m venv myenv
source myenv/bin/activate  # On Mac/Linux
# OR: myenv\Scripts\activate  # On Windows
pip install requests  # Now installs to venv

2. Committing the virtual environment directory

# Wrong - committing entire venv directory
git add myenv/
git commit -m "Add virtual environment"

# Correct - only commit requirements.txt
# Add to .gitignore:
echo "myenv/" >> .gitignore
echo "venv/" >> .gitignore
echo "env/" >> .gitignore

git add requirements.txt
git commit -m "Add dependencies"

3. Forgetting to update requirements.txt

# Wrong - install package but forget to save
pip install new-package==1.2.3
# requirements.txt is now out of date!

# Correct - update requirements.txt after installing
pip install new-package==1.2.3
pip freeze > requirements.txt  # Update immediately

# Or better yet, install from requirements directly
pip install -r requirements.txt

4. Creating venv inside project that's already in venv

# Wrong - nested virtual environments
source myenv/bin/activate  # Already in venv
python -m venv nested_env  # Creating venv inside venv - confusing!

# Correct - deactivate first, or create in project root
deactivate  # Exit current venv
python -m venv project_env  # Create at project level

Exercise: Create a Project Environment

Task: Write a Python script that simulates setting up a new project with a virtual environment. The script should demonstrate the workflow of creating a venv, installing packages, and managing requirements.txt.

Requirements:

  • Print commands to create a virtual environment named 'myproject_env'
  • Show activation commands for both Windows and Mac/Linux
  • Demonstrate installing packages (requests, flask)
  • Show how to generate and read requirements.txt
  • Include deactivation command
Output
Click Run to execute your code
Show Solution
# Creating virtual environment
print("Step 1: Create virtual environment")
print("python3 -m venv myproject_env")

# Activating (choose based on OS)
print("\nStep 2: Activate virtual environment")
print("Windows: myproject_env\\Scripts\\activate")
print("Mac/Linux: source myproject_env/bin/activate")

# Installing packages
print("\nStep 3: Install packages")
print("pip install requests flask")

# Generate requirements
print("\nStep 4: Save dependencies")
print("pip freeze > requirements.txt")

# Deactivate
print("\nStep 5: Deactivate when done")
print("deactivate")

# Recreate environment (for deployment)
print("\nTo recreate environment:")
print("python3 -m venv myproject_env")
print("source myproject_env/bin/activate  # or Scripts\\activate on Windows")
print("pip install -r requirements.txt")

Summary

  • Virtual Environments: Isolated Python environments for each project to avoid dependency conflicts
  • Creating: Use python3 -m venv env_name to create a new virtual environment
  • Activating: source env_name/bin/activate (Mac/Linux) or env_name\Scripts\activate (Windows)
  • Deactivating: Simply run deactivate
  • Installing Packages: Use pip install package while venv is activated
  • requirements.txt: Generate with pip freeze > requirements.txt, install with pip install -r requirements.txt
  • Best Practice: Always use virtual environments for projects, commit requirements.txt to version control, never commit the venv directory

What's Next?

Virtual environments are essential for professional development! Next, we'll explore unit testing with Python's unittest module. Testing ensures your code works correctly and helps catch bugs before they reach production. Writing tests is a critical professional practice!