Python

Python Virtual Environments: A Practical Guide for Developers

When you start learning Python, installing a package is usually pretty simple. You run a command like pip install requests, import the package into your code,…

D
DevByteTechnical Author
Published
9 min read4 views
Python Virtual Environments: A Practical Guide for Developers

When you start learning Python, installing a package is usually pretty simple. You run a command like pip install requests, import the package into your code, and everything works.

But things can get confusing when you start working on multiple Python projects.

Imagine you are building two applications. One project uses Django 4, while another needs Django 5. Or maybe one application depends on an older version of a package, but your new project requires the latest version.

If both projects use the same Python environment, changing a package for one project can break the other.

This is where Python virtual environments become useful.

A virtual environment allows you to create an isolated Python environment for a particular project. Each project can have its own packages and dependencies without affecting other projects on your machine.

In this article, we’ll understand what virtual environments are, why developers use them, how to create and activate them, and how to manage dependencies in real projects.

What Is a Python Virtual Environment?

A Python virtual environment is an isolated environment that contains a Python interpreter and a separate location for installing project-specific packages.

In simple words, it gives each project its own package setup.

Without a virtual environment, packages are often installed into a shared Python environment. With a virtual environment, packages installed for one project stay separate from packages installed for another.

For example, consider this project structure:

project-a/
    app.py
    requirements.txt

project-b/
    app.py
    requirements.txt

Project A might use one version of Flask, while Project B uses another. A virtual environment helps keep those dependencies separate.

This is especially useful when working on:

  • Multiple Python projects

  • Django or Flask applications

  • FastAPI backends

  • Data science projects

  • Automation scripts

  • AI and machine learning applications

If you are developing APIs with FastAPI or experimenting with different AI libraries, using virtual environments can save you from a lot of dependency-related headaches.

Why Do We Need Virtual Environments?

Let's look at a practical example.

Suppose you have two projects:

  • Project A uses requests version 2.28.

  • Project B uses requests version 2.32.

If both projects share the same environment, installing or upgrading the package for Project B could affect Project A.

This can lead to unexpected errors.

A virtual environment solves this by separating the package installations.

1. Avoid dependency conflicts

Different projects can require different versions of the same package.

For example:

Project A:
    Django 4.x

Project B:
    Django 5.x

Each project can install its own version inside its own environment.

2. Keep the global Python installation clean

Installing every package globally can make your Python installation difficult to manage.

You might install a package for a quick experiment and later forget that it is there.

Virtual environments keep project dependencies organized.

3. Make projects easier to share

When you work with another developer, you need a reliable way to tell them which packages your project requires.

A dependency file such as requirements.txt makes it easier to recreate the environment on another machine.

4. Reduce accidental breakage

Upgrading a library in one project should not unexpectedly change the dependencies of another project.

Virtual environments help reduce this risk.

Creating a Python Virtual Environment

Python includes a built-in module called venv for creating virtual environments. You usually do not need to install an additional package to use it.

Let's create a simple project.

Step 1: Create a project directory

Open your terminal and run:

mkdir my-python-project
cd my-python-project

Now you are inside your project directory.

Step 2: Create a virtual environment

Run:

python3 -m venv .venv

On systems where python points to the correct Python installation, this can also be:

python -m venv .venv

Here is what the command means:

  • python3 runs the Python interpreter.

  • -m venv runs Python's built-in virtual environment module.

  • .venv is the directory where the environment will be created.

The name .venv is a common convention. You could call it venv or something else, but .venv is easy to recognize and is commonly used by editors such as VS Code.

After creating it, your project may look like this:

my-python-project/
    .venv/
    app.py

The .venv directory contains the environment's files. You generally should not manually edit those files.

Activating the Virtual Environment

Creating a virtual environment does not automatically activate it.

Activation changes your shell's environment so that Python and pip commands use the virtual environment.

The activation command depends on your operating system and shell.

macOS and Linux

source .venv/bin/activate

Windows Command Prompt

.venv\Scripts\activate.bat

Windows PowerShell

.venv\Scripts\Activate.ps1

Once activated, your terminal prompt will often show the environment name:

(.venv) $

This is a visual indication that the environment is active.

You can check which Python executable is being used:

which python

On macOS or Linux, the output should point to the Python executable inside your .venv directory.

On Windows, use:

where python

If the output points to your project’s virtual environment, you are using the correct Python interpreter.

Installing Packages Inside a Virtual Environment

Once the environment is activated, you can install packages normally.

For example:

python -m pip install requests

Using python -m pip helps ensure that pip belongs to the Python interpreter you are currently using.

You can check the installed packages:

python -m pip list

You might see output similar to:

Package    Version
---------- -------
pip        24.x
requests   2.32.x

The exact versions will depend on what is installed.

Now create a simple Python file:

import requests

response = requests.get("https://example.com")

print(response.status_code)

Run it:

python app.py

The package will be available because it was installed inside the active virtual environment.

Managing Dependencies with requirements.txt

In a real project, you will probably install more than one package.

For example, a FastAPI application might use:

python -m pip install fastapi uvicorn

You can save the installed packages into a file:

python -m pip freeze > requirements.txt

This creates a requirements.txt file containing the package versions currently installed in the environment.

It may look something like this:

fastapi==0.x.x
uvicorn==0.x.x

The exact versions depend on your installation.

The file is useful when sharing the project with another developer or deploying it to a server.

Installing dependencies from requirements.txt

When another developer clones your project, they can create and activate their own virtual environment, then run:

python -m pip install -r requirements.txt

This installs the packages listed in the file.

A typical workflow looks like this:

git clone https://github.com/example/my-python-project.git
cd my-python-project

python3 -m venv .venv
source .venv/bin/activate

python -m pip install -r requirements.txt

The Git URL above is only an example. Replace it with your actual repository URL.

This is one of the most common workflows in Python development.

A Practical Example: Setting Up a FastAPI Project

Let's use what we have learned to set up a small FastAPI project.

Step 1: Create the project

mkdir fastapi-demo
cd fastapi-demo

Step 2: Create and activate the environment

python3 -m venv .venv
source .venv/bin/activate

Step 3: Install FastAPI and Uvicorn

python -m pip install fastapi uvicorn

Step 4: Create main.py

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def home():
    return {"message": "Hello from FastAPI"}

Step 5: Run the application

uvicorn main:app --reload

Here:

  • main is the Python file name, without .py.

  • app is the FastAPI object.

  • --reload restarts the development server when your code changes.

Your API will be available locally at:

http://127.0.0.1:8000

FastAPI also provides interactive API documentation at:

http://127.0.0.1:8000/docs

You can now save the dependencies:

python -m pip freeze > requirements.txt

You have a basic FastAPI project running inside an isolated Python environment.

Deactivating a Virtual Environment

When you finish working on a project, you can deactivate the environment:

deactivate

This returns your shell to its previous Python environment.

The virtual environment is not deleted. It remains in your project directory and can be activated again whenever you need it.

For example:

cd fastapi-demo
source .venv/bin/activate

You do not need to recreate the environment every time you open the project.

Should You Add .venv to Git?

This is a common question when setting up a Python project.

The short answer is: No, you generally should not commit the virtual environment directory to Git.

The .venv directory can contain many files and packages. It can also include paths specific to your machine.

Instead, add it to your .gitignore file:

.venv/
venv/
__pycache__/
*.pyc

Then commit your source code and dependency files:

my-python-project/
    .venv/
    .gitignore
    app.py
    requirements.txt

The .venv folder stays on your machine, while other developers can recreate their own environments using requirements.txt.

Common Virtual Environment Problems

Even though virtual environments are simple, beginners sometimes run into a few common issues.

Problem 1: The package is installed, but Python cannot import it

This often happens when you install a package in one environment but run the code using another Python interpreter.

Check the active Python path:

which python

Then check where pip installs packages:

python -m pip --version

If the paths do not point to your virtual environment, activate the correct environment or select the correct interpreter in your editor.

Problem 2: The activation command does not work

Make sure you are inside the project directory and that the .venv directory exists.

For macOS and Linux:

ls .venv/bin

For Windows:

dir .venv\Scripts

Also, remember that activation commands differ between operating systems.

Problem 3: PowerShell blocks activation

On Windows, PowerShell may block the activation script due to its execution policy.

You can use Command Prompt instead, or review Microsoft's PowerShell execution-policy documentation before changing policy settings.

Avoid changing security settings blindly just to activate an environment.

Problem 4: The environment stops working after moving the project

Virtual environments are generally not portable. They can contain paths tied to their original location.

If you move a project to a different directory and the environment no longer works, the simplest solution is usually to recreate it:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt

This is another reason not to commit .venv to Git.

Virtual Environment vs Python Interpreter

These two terms are related, but they are not exactly the same.

A Python interpreter is the program that runs Python code.

A virtual environment is an isolated setup that uses a Python interpreter and maintains its own package installation location.

For example, you may have Python installed on your computer and create several virtual environments from it:

Computer
│
├── Python installation
│
├── Project A
│   └── .venv
│       └── Project A packages
│
└── Project B
    └── .venv
        └── Project B packages

This setup allows both projects to use Python while keeping their dependencies separate.

Best Practices for Python Virtual Environments

Here are a few habits that make Python projects easier to maintain:

  1. Create a virtual environment for each project.

  2. Use a consistent name such as .venv.

  3. Activate the environment before installing packages or running your application.

  4. Use python -m pip to make sure packages are installed for the intended interpreter.

  5. Keep dependency information in requirements.txt or another dependency-management file.

  6. Add .venv to .gitignore.

  7. Recreate the environment when moving a project instead of manually copying it.

  8. Make sure your IDE or code editor uses the correct interpreter.

For larger projects, tools such as Poetry or uv can help manage dependencies and project configuration. But you do not need to start with them. Python's built-in venv module is enough for many projects.

Conclusion

Python virtual environments are one of those tools that may seem optional when you are learning the language, but they quickly become essential when you work on real projects.

They help keep dependencies separate, prevent package conflicts, and make it easier to share your code with other developers.

The basic workflow is straightforward: create an environment, activate it, install your packages, save your dependencies, and use the same environment while working on the project.

Once you make this a habit, setting up Python projects becomes much more predictable.

Whether you are building a FastAPI backend, working on a Django application, writing automation scripts, or experimenting with AI libraries, a virtual environment is a good place to start.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘