Course contentsShow
← Python
Lesson 496 of 1,0608. Professional Tooling and PackagingFree lesson

Creating Isolated Environments Using Venv

Master the creation of lightweight, local Python environments that contain their own site directories to keep project dependencies completely separated.

In this lesson, you will learn how to create isolated Python environments to prevent dependency conflicts and keep your project’s global workspace clean.

As you build increasingly complex systems, you likely rely on third-party libraries. If you install these packages globally, you risk "dependency hell"—a situation where Project A requires Version 1.0 of a library, but Project B requires Version 2.0. Because the global Python site-packages directory can only hold one version at a time, you are forced to choose, often breaking one of your projects.

The venv (Virtual Environment) module solves this by creating a self-contained directory tree that contains its own Python executable and a dedicated site-packages folder. When you "activate" this environment, your shell points to this local folder instead of the global one.

Creating and Activating an Environment

To create a new environment in your project folder, run the following command in your terminal:

python -m venv .venv

This creates a folder named .venv containing a copy of the Python interpreter and a set of standard utilities. To start using it, you must activate it. On macOS or Linux, run:

source .venv/bin/activate

On Windows, run:

.venv\Scripts\activate

Once activated, your command prompt will usually show (.venv). Any package you install via pip will now be physically stored inside that folder, completely invisible to other projects on your machine. You can verify this by running which python (on Unix) or where python (on Windows), which will point directly into your local .venv directory.

When you are done working, simply type deactivate to return to your global system environment. This workflow ensures that your project remains portable and predictable, as you can easily generate a list of dependencies that are guaranteed to work within that specific, isolated sandbox.

Key Takeaway: Using venv creates a project-specific sandbox, ensuring that your application's dependencies remain consistent and isolated from your global system and other projects.