Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes

Create Virtual Environments

Learn to create virtual environments with venv in Python. This step-by-step lesson covers why you need isolated environments, how to create and activate them, and best practices for managing project dependencies.

Focus: create virtual environments with venv

Sponsored

You've mastered Python syntax, written your first scripts, and maybe even installed a third‑party package with pip. But soon you'll hit a wall: one project needs Flask 2.0, another requires Django 4.2, and a third still depends on an old library that breaks with newer versions. Without isolated Python environments, you're stuck in dependency hell — where upgrading one project silently breaks another. This lesson teaches you how to create virtual environments with venv, Python's built‑in tool for keeping each project's dependencies clean, separate, and conflict‑free.

The problem this lesson solves

Imagine you clone a colleague's project and run pip install — only to discover it needs requests==2.25.1, while your other project expects requests==2.31.0. If you upgrade the system‑wide package, you might break the first project. Downgrade, and the second stops working. You can't win.

This is the global environment trap. Python normally installs packages into a single system‑wide location (/usr/lib/python3.X/site-packages). Every project shares the same set of packages — a disaster when versions conflict.

Virtual environments solve this by creating a fresh, lightweight copy of Python inside a folder per project. Packages you install in that folder stay isolated from everything else. No more version conflicts, no more sudo pip install accidents, no more "it works on my machine" headaches.

Pro tip: Always use a virtual environment for every project, even a small one‑file script. It's a habit that will save you hours of debugging.

Core concept / mental model

Think of a virtual environment as a clean hotel room for your Python project. The room has its own closet (the site‑packages folder) where you can hang your specific packages. You can check in and check out of different rooms without cluttering the hallway (your global Python).

Here's what venv actually does under the hood:

  1. Creates a new directory (commonly called venv or .venv)
  2. Copies or symlinks the python binary and pip into it
  3. Sets up its own site‑packages folder — empty at first
  4. Provides activation scripts that temporarily modify your shell's PATH so python and pip point to the isolated environment

The key insight: venv is not a virtual machine — it doesn't emulate hardware. It's just a lightweight directory structure that isolates Python packages. It ships with Python 3.3+ and requires no extra downloads.

How it works step by step

1. Create the environment

Navigate to your project folder and run:

python -m venv venv
  • python -m venv tells Python to run the venv module as a script.
  • The second venv is the name of the folder that will contain the isolated environment. (You can name it anything, but venv or .venv are community conventions.)

After running, you'll see a new venv directory with: * bin/ (or Scripts on Windows) – contains the Python executable and activation scripts * lib/ (or Lib on Windows) – contains site‑packages * pyvenv.cfg – configuration file pointing to the system Python

2. Activate the environment

Before using the new environment, you must activate it. Activation modifies your shell so that python and pip refer to the isolated versions.

macOS / Linux / Git Bash:

source venv/bin/activate

Windows (Command Prompt):

venv\Scripts\activate

Windows (PowerShell):

.\venv\Scripts\Activate.ps1

When activation succeeds, you'll see the environment name in your shell prompt:

(venv) $ python --version
Python 3.10.12

3. Install packages inside the environment

Now you can install project dependencies without affecting the entire system:

(venv) $ pip install requests==2.31.0
Collecting requests==2.31.0
  Downloading requests-2.31.0-py3-none-any.whl (62 kB)
Installing collected packages: requests
Successfully installed requests-2.31.0

Check that installed packages live inside the venv's site‑packages, not globally:

(venv) $ pip list
Package    Version
---------- -------
pip        23.0.1
requests   2.31.0
setuptools 67.6.0

4. Deactivate when done

When you finish working, return to the global environment:

(venv) $ deactivate
$ python --version   # back to system Python

The deactivate command restores your original PATH — the environment's Python and commands will no longer be accessible.

Hands-on walkthrough

Let's put everything together with a complete, runnable example.

Example 1: Create, activate, install, and deactivate

# 1. Create a new project directory
mkdir my_flask_app && cd my_flask_app

# 2. Create a virtual environment named 'venv'
python -m venv venv

# 3. Activate it
source venv/bin/activate

# 4. Verify we are using the venv's Python
which python
# Output: /home/user/my_flask_app/venv/bin/python

# 5. Install Flask
pip install flask

# 6. Create a minimal Flask app
cat > app.py << 'EOF'
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello from inside a venv!"

if __name__ == '__main__':
    app.run()
EOF

# 7. Run the app (it uses the venv's Python and packages)
python app.py
# Output: * Running on http://127.0.0.1:5000

# 8. Deactivate when finished
deactivate

Example 2: Check isolation with two environments

Create two separate environments and install different package versions:

# Create project A
mkdir project_a && cd project_a
python -m venv venv
source venv/bin/activate
pip install requests==2.25.1
deactivate

# Create project B
mkdir ../project_b && cd ../project_b
python -m venv venv
source venv/bin/activate
pip install requests==2.31.0
deactivate

# Both requests versions coexist safely because each lives inside its own venv!

Pro tip: Run pip freeze > requirements.txt after installing your packages to record exact versions. This file allows anyone else (or your future self) to recreate the same environment with pip install -r requirements.txt.

Example 3: Using a .gitignore for the venv directory

Never commit your virtual environment to version control. Add this line to .gitignore:

# .gitignore
venv/
.venv/

Other contributors recreate the environment from requirements.txt.

Compare options / when to choose what

Python offers several tools for managing environments. Here's a quick comparison:

Tool Built‑in? Use case Ecosystem support
venv Yes (Python 3.3+) Simple, lightweight isolation; best for beginners and basic projects Everywhere – the default choice
virtualenv No (external package) Older projects (Python 2); more features like custom interpreters Legacy – newer Python versions recommend venv
conda No (Anaconda/Miniconda) Data science, non‑Python packages (e.g., C libraries, R) Strong for scientific computing
pipenv No (external package) Combines Pipfile, Pipfile.lock, and venv; opinionated Niche – development teams with specific workflows
poetry No (external package) Dependency management + packaging; modern alternative Growing popularity, but heavier

When to choose venv: * You're writing a standard Python application (web, CLI, script). * You want zero extra dependencies. * You need a straightforward, cross‑platform solution.

When to choose an alternative: * conda – if your project involves NumPy, pandas, or other compiled libraries tied to non‑Python system packages. * poetry – if you need a full‑featured dependency resolver and package publisher.

Pro tip: For this tutorial track and most everyday Python projects, stick with venv. It's the most widely understood, requires no extra installation, and is supported in every CI/CD pipeline.

Troubleshooting & edge cases

"python command not found" after activation

You might have multiple Python versions installed. Always create the environment with the exact version you need:

python3.10 -m venv venv
# then activate normally

Activation command fails on Windows PowerShell

PowerShell's execution policy may block scripts. To enable it for the current session:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Or run venv\Scripts\activate.bat from Command Prompt instead.

Accidentally committed venv/ to Git

If you already committed it, remove it from tracking:

echo "venv/" >> .gitignore
git rm -r --cached venv
git commit -m "Remove venv from repo"

deactivate not working

Some shell configurations may override the command. Try:

# Fish shell
functions -e deactivate

# Close and reopen the terminal window

Environment created outside project folder

You can place the venv directory anywhere, but best practice keeps it inside the project root. That way deleting the project folder also removes the environment.

Permission denied when creating venv

You need write permission in the target directory. Avoid using sudo with venv – it often creates environment files owned by root. Instead, choose a directory you control (your home folder or project folder).

What you learned & what's next

You now know how to create virtual environments with venv — a fundamental skill for every Python developer.

Here's what you accomplished:

  • Explained the core idea – isolated project environments prevent dependency conflicts.
  • Created, activated, and deactivated a virtual environment.
  • Installed packages inside the isolated space without affecting the global system.
  • Understood the mental model – each environment is a clean hotel room for your project's dependencies.
  • Compared venv to other tools like conda and pipenv.
  • Handled common pitfalls – permission issues, shell activation, and version mismatches.

Now that you can create isolated environments, the next lesson will show you how to save and restore dependencies using requirements.txt and pip freeze — making your projects reproducible and shareable.

Continue your journey to become a confident Python developer. You've mastered isolation — next comes packaging for portability.

Practice recap

Now it's your turn: Create a new directory called practice_venv, inside it run python -m venv myenv, activate it, install the cowsay package, and run cowsay "Virtual environments are cool!". Then deactivate and verify that cowsay is no longer available globally. This simple exercise reinforces the core isolation concept.

Common mistakes

  • Activation appears to succeed but which python still shows the system Python — usually because you typed source venv/bin/activate.sh instead of source venv/bin/activate.
  • Creating the venv with sudo — this changes the ownership of files to root, causing permission errors later. Always create venv under your user directory.
  • Forgot to call deactivate before working on another project — you'll accidentally install new packages into the first environment instead of a fresh one.
  • Committing the venv/ folder to Git — this bloats the repository and breaks reproducibility. Add venv/ to .gitignore immediately after creating the environment.

Variations

  1. Use .venv/ as the directory name (hidden folder) instead of venv/ — both are community standards, but .venv keeps your project root tidier.
  2. Use virtualenv which supports Python 2 and offers more advanced options like custom Python interpreters — useful for legacy projects.
  3. Use conda create --name myenv python=3.10 for environments that need non-Python packages (e.g., C libraries for scientific computing).

Real-world use cases

  • Developing a web application that requires an exact version of Flask and its dependencies, isolated from other Python projects on the same machine.
  • Running a legacy script that depends on requests==2.25.1 while simultaneously managing a modern API service using requests==2.31.0.
  • Setting up a continuous integration (CI) pipeline that creates a fresh environment per build from requirements.txt to ensure reproducible tests.

Key takeaways

  • venv is a lightweight, built‑in tool for creating isolated Python environments — no extra installation needed.
  • Always create a virtual environment inside your project folder and add the directory to .gitignore.
  • Activate the environment with source venv/bin/activate (Linux/macOS) or venv\Scripts\activate (Windows) before installing packages.
  • Use pip freeze > requirements.txt to save exact package versions, enabling any teammate or CI system to recreate the environment.
  • Stick with venv for standard Python projects; consider conda for scientific computing or poetry for full dependency management.
  • Never use sudo with venv — it causes permission issues that are tedious to fix.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.