Virtual Environments in Python | Python Course | Dataplexa

Virtual Environments in Python

Every Python project you build will eventually depend on external packages — web frameworks, data libraries, HTTP clients, and more. Without a system to manage those dependencies, packages from different projects collide, version conflicts break things silently, and sharing your project with others becomes a guessing game. Virtual environments solve all of this by giving each project its own isolated Python installation with its own packages.

This lesson covers creating, activating, and managing virtual environments, working with pip, freezing dependencies, the professional project workflow, IDE integration, and when to use conda instead.

The Problem Virtual Environments Solve

Imagine two projects on the same machine:

  • Project A needs requests==2.28.0
  • Project B needs requests==2.31.0

Without virtual environments, only one version can be installed globally. Installing for one project silently breaks the other. Virtual environments eliminate this by creating a completely separate package space per project — installing into one has zero effect on any other.

# Visualising the problem without virtual environments

# Global Python (system-level)
# ├── requests 2.28.0   ← Project A needs this
# └── requests 2.31.0   ← Project B needs this
#     ERROR: only ONE version can be installed at a time

# With virtual environments — each project has its own space:
# project_a/
# └── venv/
#     └── site-packages/
#         └── requests 2.28.0   ← completely isolated

# project_b/
# └── venv/
#     └── site-packages/
#         └── requests 2.31.0   ← completely isolated

# No conflict. No breakage. Both work perfectly.

Creating a Virtual Environment

Python ships with the venv module built in — no installation needed. One command creates the environment in the current directory.

# Run in your terminal — not inside Python

# Create a virtual environment named "venv"
# python -m venv venv

# On some Mac/Linux systems you may need:
# python3 -m venv venv

# Use .venv (hidden folder) — common convention on Mac/Linux
# python -m venv .venv

# The folder structure created:
# venv/
# ├── bin/             ← Mac/Linux   (Scripts/ on Windows)
# │   ├── python       ← this project's Python interpreter
# │   ├── pip          ← this project's pip
# │   └── activate     ← activation script
# ├── lib/
# │   └── python3.x/
# │       └── site-packages/   ← your packages install here only
# └── pyvenv.cfg       ← points back to the system Python
  • venv and .venv are both common names — either works. .venv hides the folder on Mac/Linux.
  • The environment folder should never be committed to version control — add it to .gitignore.
  • python -m venv venv uses whichever python is on your PATH — the created environment inherits that Python version.

Activating and Deactivating

Creating the environment does not automatically use it. You must activate it first. Activation modifies your terminal session so python and pip point to the environment's versions instead of the system ones.

# Activation — run in terminal, not in Python

# Mac / Linux:
# source venv/bin/activate

# Windows — Command Prompt:
# venv\Scripts\activate.bat

# Windows — PowerShell:
# venv\Scripts\Activate.ps1

# After activation, your prompt shows the environment name:
# (venv) user@machine:~/project$

# Confirm you are using the environment's Python:
# which python          ← Mac/Linux
# where python          ← Windows

# Check the Python location — should be inside venv/
# python -c "import sys; print(sys.executable)"

# Deactivate — return to system Python (never deletes anything)
# deactivate
  • The (venv) prefix in your terminal prompt confirms the environment is active.
  • When activated, python and pip refer exclusively to the environment.
  • deactivate restores the system Python — it never deletes or modifies the environment.
  • You must activate the environment every time you open a new terminal session.

Installing Packages with pip

With the environment active, pip install installs packages exclusively into that environment. Nothing touches the system Python or any other project.

# pip commands — run in terminal with environment active

# Install a single package
# pip install requests

# Install a specific version — critical for reproducibility
# pip install requests==2.31.0

# Install a minimum version
# pip install "requests>=2.28"

# Install multiple packages at once
# pip install flask pandas numpy matplotlib

# Upgrade a package to its latest version
# pip install --upgrade requests

# Uninstall a package
# pip uninstall requests

# List all installed packages and their versions
# pip list

# Show full details about one package (version, deps, homepage)
# pip show requests

# Search for packages (requires network)
# pip index versions requests   ← list all available versions
  • Always activate the environment before running pip install — otherwise packages go into the system Python.
  • pip install package==version pins an exact version — essential for consistent deployments.
  • pip list shows only the packages in the active environment, not the system.

Freezing Dependencies — requirements.txt

A requirements.txt file lists every package and exact version your project needs. It is the standard way to share dependencies so anyone can recreate the same environment exactly — in one command.

# requirements.txt workflow

# Step 1 — Generate the file from your active environment
# pip freeze > requirements.txt

# The file looks like this:
# certifi==2024.2.2
# charset-normalizer==3.3.2
# click==8.1.7
# flask==3.0.2
# idna==3.6
# requests==2.31.0
# urllib3==2.2.1

# Step 2 — Install from requirements.txt (teammate / deployment)
# pip install -r requirements.txt

# Tip: keep a minimal requirements.in for human editing
# and generate requirements.txt from it with pip-tools:
# pip install pip-tools
# pip-compile requirements.in   ← generates pinned requirements.txt

# Check which packages are outdated
# pip list --outdated
  • pip freeze outputs every installed package and exact version — redirect to a file with >.
  • pip install -r requirements.txt installs everything listed — recreates the environment exactly.
  • Re-run pip freeze > requirements.txt every time you add, remove, or upgrade a package.
  • requirements.txt IS committed to Git. The venv/ folder is NOT.

The Complete Professional Workflow

This is the exact sequence every professional Python developer follows when starting or joining a project.

# ============================
# STARTING A NEW PROJECT
# ============================
# mkdir my_project && cd my_project   # create and enter project folder
# python -m venv venv                  # create virtual environment
# source venv/bin/activate             # activate (Mac/Linux)
# pip install requests flask           # install packages you need
# pip freeze > requirements.txt        # freeze dependencies
# echo "venv/" >> .gitignore           # never commit the env folder
# git init && git add . && git commit -m "Initial commit"

# ============================
# JOINING AN EXISTING PROJECT
# ============================
# git clone https://github.com/org/project.git
# cd project
# python -m venv venv                  # create a fresh environment
# source venv/bin/activate             # activate it
# pip install -r requirements.txt      # install exact dependencies
# python app.py                        # run the project

# ============================
# ADDING A NEW PACKAGE LATER
# ============================
# pip install httpx                    # install the new package
# pip freeze > requirements.txt        # update the freeze file
# git add requirements.txt && git commit -m "Add httpx"

Managing Multiple Python Versions

Sometimes projects need different Python versions — one needs 3.10, another needs 3.12. venv can target a specific Python version by calling it directly.

# Create an environment with a specific Python version

# First check what versions are installed on your system:
# python3 --version
# python3.11 --version
# python3.12 --version

# Create environment using a specific version
# python3.11 -m venv venv-py311
# python3.12 -m venv venv-py312

# Verify the Python version inside the environment
# source venv-py311/bin/activate
# python --version    ← should show 3.11.x

# Tool: pyenv — install and switch multiple Python versions easily
# https://github.com/pyenv/pyenv
# pyenv install 3.11.9
# pyenv local 3.11.9   ← sets version for this directory
# python -m venv venv  ← uses 3.11.9

Using venv in VS Code and PyCharm

  • VS Code: open Command Palette (Ctrl+Shift+P / Cmd+Shift+P), search Python: Select Interpreter, choose the venv interpreter. VS Code activates it automatically in every new terminal it opens. The active environment appears in the status bar.
  • PyCharm: go to Settings → Project → Python Interpreter, click the gear, choose Add Interpreter → Virtualenv Environment → Existing, and point it at your venv folder. PyCharm handles activation transparently.
  • Both IDEs show the active environment name in the status bar at the bottom of the window — if you see the venv name there, you are correctly isolated.

pip vs conda

You will also encounter conda, a different package and environment manager popular in data science. Here is how they compare.

Featurepip + venvconda
Package sourcePyPI — Python packages onlyConda channels — Python + C/C++ libraries
Built into PythonYes — no setup neededNo — requires Anaconda or Miniconda
Handles non-Python depsNoYes — CUDA, MKL, etc.
Environment creationpython -m venv venvconda create -n myenv python=3.11
Activationsource venv/bin/activateconda activate myenv
Best forWeb dev, general Python, APIsData science, ML, scientific computing
Industry standardMost common overallCommon in data / ML teams

Practice

What command creates a virtual environment named venv in the current directory?



What command saves all installed packages and exact versions to a file?



What command installs all packages listed in a requirements.txt file?



Should the venv/ folder be committed to a Git repository?



What terminal command deactivates an active virtual environment?



What is the activation command on Mac/Linux?



Quick Quiz

What is the main purpose of a virtual environment?





What happens when you run pip install requests without activating a virtual environment first?





What does the (venv) prefix in the terminal prompt indicate?





Which file should be committed to version control to share project dependencies?





Which module built into Python is used to create virtual environments?





Which tool is better suited for data science projects that depend on non-Python libraries like CUDA or MKL?





NEXT UP
Python Libraries Overview
A tour of the most important standard library and third-party packages every Python developer should know — from os and pathlib to requests, pandas, and FastAPI.