Virtual Environments

Published by Brayan K

A virtual environment is an isolated, per-project Python installation that keeps each project's packages and versions separate, so dependencies never clash and your installs stay reproducible.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Each Python installs packages into a folder of its own

A virtual environment keeps one project's packages apart from other projects' and from the Python your computer came with. A list of pinned versions lets you rebuild the same set of packages on the same Python version and the same kind of computer. Neither stops two packages inside one project from needing different versions of a third; the last part of this lesson shows what pip does then. Packaging & Publishing Python Libraries to PyPI picks up from here, with a library's own list of what it needs.

Modules and Packages installed a package with python -m pip install requests and said why it's python -m pip: that runs the pip that belongs to that python, so the package goes where that Python looks for it. Every Python on a computer has a folder for installed packages, called site-packages, which is one of the folders in its sys.path, and pip installs into the site-packages of the Python it belongs to.

A bare pip is whichever pip the terminal finds first. A terminal looks for a command in the folders listed in a setting called PATH, in order. --version shows which Python a pip belongs to:

pip --version
python3 -m pip --version

On the Ubuntu 24.04 computer these lessons were checked on, pip --version printed pip 24.0 from /usr/lib/python3/dist-packages/pip (python 3.11): a pip that installs into Python 3.11, though Python 3.12 was installed as well, and python3.12 -m pip --version ended (python 3.12). The Python named in brackets at the end is the one that gets the package.

That computer's Python 3.12 takes no packages from pip at all. Ubuntu marks its own Python as managed by the system, so pip install stops with error: externally-managed-environment, and the message suggests the way round it: create a virtual environment, and install into that.

A virtual environment is a folder with its own site-packages

Python's venv module makes one. In your project's folder, give it the name of the folder to create, here .venv:

python3 -m venv .venv

On Windows the command starts with python, as Introduction to Python explained. It prints nothing. Measured on Python 3.10 to 3.14, the new folder holds:

From Python 3.13, venv also writes a .gitignore file into the folder, whose * line tells Git to leave the whole folder out. With an older Python, add .venv/ to your project's own .gitignore: a venv is never shared, for a reason the next part shows.

Activating a venv makes python and pip in that terminal mean the venv's. The command depends on the shell:

Where you type itCommand
macOS or Linux, in bash or zshsource .venv/bin/activate
Windows Command Prompt.venv\Scripts\activate.bat
Windows PowerShell.venv\Scripts\Activate.ps1

Python's venv documentation notes that PowerShell may first need Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser before it runs the script.

Measured in bash, activating changes three things: it puts .venv/bin at the front of PATH, so python, python3 and pip are found there first; it sets VIRTUAL_ENV to the venv's folder; and it starts the prompt with (.venv). deactivate puts all three back.

That's all activating does. The venv's Python is .venv/bin/python (.venv\Scripts\python.exe on Windows) whether the venv is active or not, and .venv/bin/python -m pip install packaging installs into it from any terminal. In the words of Python's documentation, "You don't specifically need to activate a virtual environment, as you can just specify the full path to that environment's Python interpreter when invoking Python."

A program can tell whether it's running in a venv. There, sys.prefix is the venv's folder and sys.base_prefix the Python it was made from, so the two differ; Python's documentation gives this test. This site's editor doesn't run in a venv, so here it prints False. Run by your venv's Python, active or not, the same lines print True.

import sys

print(sys.prefix != sys.base_prefix)

A venv stays where it was made

A venv records where it is: pyvenv.cfg names folders by their full paths, and so does the pip command in bin, which starts the venv's Python by its full path. So a venv that's moved half works. Measured after mv .venv moved-venv: moved-venv/bin/python still ran and found the packages installed in it, but moved-venv/bin/pip failed with an error ending in not found: it still started the Python at the old path, .venv/bin/python3.12.

Python's documentation describes a venv as "Not considered as movable or copyable -- you just recreate the same environment in the target location". So you don't move, copy or commit one. You keep a list of what's installed in it, and make a new venv wherever you need one.

pip freeze lists what's installed, and a requirements file installs it again

With the venv active, python is the venv's on every system, so the commands from here on are the same everywhere. pip freeze prints what's installed, one name==version line each:

python -m pip install packaging
python -m pip freeze

In a new venv, pip freeze printed nothing at all on Python 3.10 to 3.14: it leaves out pip, and setuptools where a venv has it. After the install it printed packaging==26.3, the version that was installed. Its lines are what a requirements file holds, so you save them with the terminal's >, which sends what a command prints into a file. In a new venv, -r installs everything the file names:

python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt

pip freeze lists everything installed, not just what you asked for. Measured on all five versions: a requirements-dev.txt holding the two lines -r requirements.txt and rich==15.0.0 installed packaging and rich, and with them markdown-it-py, Pygments and mdurl, which rich needs (mdurl through markdown-it-py). Freeze then listed all five. python -m pip uninstall -y rich removed rich alone (-y answers pip's confirmation question): the three it had brought stayed installed, and freeze kept listing them.

That -r line inside a file pulls in another file, so a project can keep two lists: requirements.txt for what the program needs to run, and requirements-dev.txt, which starts with -r requirements.txt and adds the tools for working on it, such as pytest.

Pins have limits. A package installed from a file on your own disk freezes as name @ file:///… with that file's full path, which no other computer has. And pip's help for its newer pip lock command says a lock file "is only guaranteed to be valid for the current python version and platform". A pinned requirements file has the same limit, since a package can need different things in different places. Measured: after python -m pip install build, freeze listed tomli on Python 3.10 but not on 3.12 or 3.14, because build 1.6.1 declares that it needs tomli only on Pythons before 3.11, and colorama only on Windows.

Version numbers compare as versions, not as text

pip compares version numbers by rules of their own, set out in a Python standard, PEP 440. The packaging library, which pip itself uses, applies those rules, so you can try them here. It isn't part of Python: this site's editor loads it when a program imports it, and on your computer it's python -m pip install packaging.

from packaging.version import Version

print("1.10" > "1.9")
print(Version("1.10") > Version("1.9"))
print(sorted(["1.9", "1.10", "1.2"]))
print(sorted(["1.9", "1.10", "1.2"], key=Version))

# ✅ Expected output:
# False
# True
# ['1.10', '1.2', '1.9']
# ['1.2', '1.9', '1.10']

As text, "1.10" comes before "1.9", because the character 1 sorts before 9. Version compares the numbers one by one, and 10 is more than 9; given as key=, it sorts a list the same way. A version's numbers can be read one at a time:

from packaging.version import Version

v = Version("2.32.3")
print(v.major, v.minor, v.micro)
print(v.release)
print(Version("3.0.0rc1").is_prerelease, Version("3.0.0").is_prerelease)

# ✅ Expected output:
# 2 32 3
# (2, 32, 3)
# True False

Version also reads the other spellings a version may come in, and gives each one standard form: a leading v goes, -beta becomes b0, and -rc.2 becomes rc2. a, b and rc mark pre-releases, test versions that come before the release (alpha, beta and release candidate), and .post1 marks a post-release, commonly used for corrections to packaging or release notes. The version label alone does not prove that the code stayed unchanged:

from packaging.version import Version

for text in ["1.0", "1.0.0", "v1.0", "1.0-beta", "1.0.post1", "1.0a1", "2.0-rc.2", "2024.10.6"]:
    print(f"{text:<10} -> {Version(text)}")

# ✅ Expected output:
# 1.0        -> 1.0
# 1.0.0      -> 1.0.0
# v1.0       -> 1.0
# 1.0-beta   -> 1.0b0
# 1.0.post1  -> 1.0.post1
# 1.0a1      -> 1.0a1
# 2.0-rc.2   -> 2.0rc2
# 2024.10.6  -> 2024.10.6

Missing numbers count as zeros, so 2.0 and 2.0.0 are the same version, though not the same text:

from packaging.specifiers import SpecifierSet
from packaging.version import Version

print(Version("2.0") == Version("2.0.0"))
print("2.0" == "2.0.0")
print("2.0.0" in SpecifierSet("==2.0"))
print("2.0.1" in SpecifierSet("==2.0"))

# ✅ Expected output:
# True
# False
# True
# False

Text that isn't a version stops with InvalidVersion:

from packaging.version import Version

print(Version("1.4.2"))
Version("1.4.x")

# ✅ Expected output:
# 1.4.2

# ✅ Expected error:
# packaging.version.InvalidVersion: Invalid version: '1.4.x'

Many projects number their versions MAJOR.MINOR.PATCH, and raise the first number when a change can break code written for the old version, a convention called semantic versioning. Python's tools don't check that promise, only the PEP 440 format, so a project's own notes say what its numbers mean.

What ==, >=, ~= and ==1.4.* let through

A specifier is the part of a requirement that limits the versions, and SpecifierSet says which versions one allows: in tests a version.

from packaging.specifiers import SpecifierSet

releases = ["1.3.9", "1.4.0", "1.4.7", "1.5.0", "1.9.2", "2.0.0"]
for spec in ["==1.4.7", ">=1.4,<2", "~=1.4", "~=1.4.0", "==1.4.*"]:
    allowed = [v for v in releases if v in SpecifierSet(spec)]
    print(f"{spec:<9} {allowed}")

# ✅ Expected output:
# ==1.4.7   ['1.4.7']
# >=1.4,<2  ['1.4.0', '1.4.7', '1.5.0', '1.9.2']
# ~=1.4     ['1.4.0', '1.4.7', '1.5.0', '1.9.2']
# ~=1.4.0   ['1.4.0', '1.4.7']
# ==1.4.*   ['1.4.0', '1.4.7']

Written out, ~=2.31 is >=2.31 and ==2.* together. The two SpecifierSet objects aren't equal, since they're written differently, but they let the same versions through:

from packaging.specifiers import SpecifierSet

print(SpecifierSet("~=2.31") == SpecifierSet(">=2.31,==2.*"))
print([v for v in ["2.30", "2.31", "2.99", "3.0"] if v in SpecifierSet("~=2.31")])
print([v for v in ["2.30", "2.31", "2.99", "3.0"] if v in SpecifierSet(">=2.31,==2.*")])

# ✅ Expected output:
# False
# ['2.31', '2.99']
# ['2.31', '2.99']

Pre-releases are a special case. pip skips them unless told otherwise: its help for --pre, the option that includes them, says "By default, pip only finds stable versions." An upper limit such as <3 also leaves out 3.0's own pre-releases, so 3.0.0rc1 doesn't slip under it, even when pre-releases are allowed:

from packaging.specifiers import SpecifierSet

spec = SpecifierSet(">=2.31,<3")
print([v for v in ["2.30.0", "2.31.0", "2.32.3", "3.0.0rc1", "3.0.0"] if v in spec])
print(spec.contains("3.0.0rc1", prereleases=True))

# ✅ Expected output:
# ['2.31.0', '2.32.3']
# False

Whether SpecifierSet counts a pre-release such as 2.1rc1 as inside >=2.0 changed between versions of packaging, so none of these examples relies on it.

=> and = aren't operators, and ~= needs at least two numbers. A specifier like those stops with InvalidSpecifier:

from packaging.specifiers import SpecifierSet

SpecifierSet("=>1.4")

# ✅ Expected error:
# packaging.specifiers.InvalidSpecifier: Invalid specifier: '=>1.4'
from packaging.specifiers import SpecifierSet, InvalidSpecifier

for text in [">=1.4", "=>1.4", "=1.4", "~=1", "~=1.4", "== 1.4"]:
    try:
        SpecifierSet(text)
        print(f"{text!r} is valid")
    except InvalidSpecifier:
        print(f"{text!r} is not")

# ✅ Expected output:
# '>=1.4' is valid
# '=>1.4' is not
# '=1.4' is not
# '~=1' is not
# '~=1.4' is valid
# '== 1.4' is valid

A space after the operator is allowed, as == 1.4 shows.

In a terminal, put a requirement that holds > or < in quotes. Measured in bash, pip install packaging>=20 ran pip install packaging with no version limit, and the shell sent pip's output into a new file named =20, since to the shell > means "write the output into a file". Python's guide to installing says such a requirement "should be enclosed within double quotes":

python -m pip install "packaging>=20"

A requirement line, and the names in it

A requirement can name extras in square brackets: optional parts of a package, which bring more packages with them. Requirement takes a whole line apart:

from packaging.requirements import Requirement

req = Requirement("requests[socks]>=2.31,<3")
print(req.name)
print(sorted(req.extras))
print(str(req.specifier))
print("2.32.3" in req.specifier, "3.0.0" in req.specifier)
print(req)

# ✅ Expected output:
# requests
# ['socks']
# <3,>=2.31
# True False
# requests[socks]<3,>=2.31

str() sorted the two specifiers. In a terminal the same line goes in quotes, for the shell's sake: python -m pip install "requests[socks]>=2.31,<3".

Package names are compared without regard to case, and -, _ and . count as the same character, a run of them as one. So PyYAML and pyyaml name one project. canonicalize_name() gives the form that's compared:

from packaging.utils import canonicalize_name

for name in ["Flask_SQLAlchemy", "flask-sqlalchemy", "Flask.SQLAlchemy", "PyYAML", "my__cool--lib"]:
    print(f"{name:<17} -> {canonicalize_name(name)}")

# ✅ Expected output:
# Flask_SQLAlchemy  -> flask-sqlalchemy
# flask-sqlalchemy  -> flask-sqlalchemy
# Flask.SQLAlchemy  -> flask-sqlalchemy
# PyYAML            -> pyyaml
# my__cool--lib     -> my-cool-lib

From inside Python, the standard library's importlib.metadata reads what's installed: version("packaging") returns the installed version as a string, from the environment the program runs in. A name that isn't installed stops with PackageNotFoundError:

from importlib.metadata import version

print(version("no-such-package-xyz"))

# ✅ Expected error:
# importlib.metadata.PackageNotFoundError: No package metadata was found for no-such-package-xyz

pip checks only what it's installing now

pip works out versions for the packages it's installing at that moment, and only for those. To show it, four small packages were made for this lesson: pkg-a 1.0 needs shared==1.0, and pkg-b 1.0 needs shared==2.0. In a new venv:

python -m pip install pkg-a pkg-b

Asked for both at once, pip found no version of shared that suits both, and installed nothing. It named the clash, pkg-a 1.0 depends on shared==1.0 and pkg-b 1.0 depends on shared==2.0, and ended with ERROR: ResolutionImpossible. Asked for one package at a time, it did something else:

python -m pip install pkg-a
python -m pip install pkg-b
python -m pip check

The second install replaced shared 1.0 with 2.0, printed an ERROR line saying pkg-a 1.0 requires shared==1.0, but you have shared 2.0 which is incompatible., and still ended with Successfully installed pkg-b-1.0 shared-2.0 and exit status 0. Then pip check printed pkg-a 1.0 has requirement shared==1.0, but you have shared 2.0. and ended with exit status 1. All of this was the same on Python 3.10 to 3.14, with pip 23.0.1 to 26.2.1, apart from some of the lines around the conflict.

So install a project's packages together, from one requirements file, so that pip sees every requirement at once, and run python -m pip check after installing anything on its own.

Practice: pick the specifiers

Fill in the two blanks so that the first set allows only the bug-fix releases of 2.31, and the second any release from 2.31 on that's still 2. The hints under the code give each one.

from packaging.specifiers import SpecifierSet

releases = ["2.30.0", "2.31.0", "2.31.4", "2.32.3", "3.0.0"]

bug_fixes_only = SpecifierSet("___")
same_major = SpecifierSet("___")

print([v for v in releases if v in bug_fixes_only])
print([v for v in releases if v in same_major])

# 👉 replace ___ with ~=2.31.0
# 👉 replace ___ with >=2.31,<3

# ✅ Expected output:
# ['2.31.0', '2.31.4']
# ['2.31.0', '2.31.4', '2.32.3']

On your own: compare a requirements file with pip freeze

A project's requirements.txt and the pip freeze output of a venv are given as two lists of name==version lines. Print a line for each package that's required but not installed (MISSING), installed at another version (WRONG), or installed but not required (EXTRA), then the number of problems. Compare names with canonicalize_name(), including dots and repeated separators. Compare versions with Version, so equivalent spellings such as 2.0 and 2.0.0 agree.

This exercise accepts only the supplied simple name==version lines, not every requirements-file form. EXTRA means absent from the supplied list; it is not advice to uninstall a package that another dependency may need.

from packaging.utils import canonicalize_name
from packaging.version import Version

required_lines = ["fastapi==0.115.0", "uvicorn==0.32.0", "PyYAML==6.0.2", "python_dotenv==1.0.1", "requests==2.32.3"]
frozen_lines = ["fastapi==0.115.0", "pyyaml==6.0.2", "python-dotenv==1.0.1", "rich==13.9.2", "uvicorn==0.30.1"]


def parse(lines):
    pins = {}
    for line in lines:
        name, version = line.split("==")
        pins[canonicalize_name(name)] = Version(version)
    return pins


required = parse(required_lines)
installed = parse(frozen_lines)
problems = 0
for name, version in required.items():
    if name not in installed:
        print(f"MISSING  {name}=={version}")
        problems += 1
    elif installed[name] != version:
        print(f"WRONG    {name}: installed {installed[name]}, required {version}")
        problems += 1
for name, version in installed.items():
    if name not in required:
        print(f"EXTRA    {name}=={version}")
        problems += 1
print(f"{problems} problems")



# ✅ Expected output:
# WRONG    uvicorn: installed 0.30.1, required 0.32.0
# MISSING  requests==2.32.3
# EXTRA    rich==13.9.2
# 3 problems

Practice quiz

With from packaging.version import Version, what does print("1.10" > "1.9", Version("1.10") > Version("1.9")) print?

  • True True
  • True False
  • False True
  • False False

Answer: False True. As text, "1.10" comes first, because the character 1 sorts before 9. Version compares the numbers, and 10 is more than 9.

Of the releases 1.4.0, 1.4.9, 1.5.0 and 2.0.0, which does ~=1.4.0 allow?

  • ['1.4.0', '1.4.9']
  • ['1.4.0', '1.4.9', '1.5.0']
  • ['1.4.0']
  • ['1.4.0', '1.4.9', '1.5.0', '2.0.0']

Answer: ['1.4.0', '1.4.9']. ~= lets the last number given grow and keeps the ones before it, so ~=1.4.0 is 1.4.0 or later, but still 1.4.

Of the same releases, 1.4.0, 1.4.9, 1.5.0 and 2.0.0, which does ~=1.4 allow?

  • ['1.4.0', '1.4.9']
  • ['1.4.0']
  • ['1.4.0', '1.4.9', '1.5.0', '2.0.0']
  • ['1.4.0', '1.4.9', '1.5.0']

Answer: ['1.4.0', '1.4.9', '1.5.0']. With two numbers given, the second may grow: ~=1.4 allows what >=1.4,<2 allows.

What does print("2.0.0" in SpecifierSet("==2.0"), "2.0.1" in SpecifierSet("==2.0")) print?

  • False False
  • True False
  • True True
  • False True

Answer: True False. Missing numbers count as zeros, so 2.0 and 2.0.0 are the same version. 2.0.1 is another one.

What does SpecifierSet("=>2.0") do?

  • The same as >=2.0
  • It stops with InvalidSpecifier: Invalid specifier: '=>2.0'
  • It allows 2.0 only
  • It stops with a SyntaxError

Answer: It stops with InvalidSpecifier: Invalid specifier: '=>2.0'. The operator is >=, with the > first. => isn't an operator, so packaging refuses the whole specifier.

In bash, you type pip install packaging>=20. What happens?

  • pip gets packaging with no version limit, and its output goes into a new file named =20
  • pip installs packaging 20 or later
  • bash stops with a syntax error
  • pip stops with Invalid requirement

Answer: pip gets packaging with no version limit, and its output goes into a new file named =20. To the shell, >=20 means "write the output into the file =20", so pip is asked for packaging alone. In quotes, "packaging>=20" reaches pip whole.

Without activating it, you run .venv/bin/python -c "import sys; print(sys.prefix != sys.base_prefix)". What prints?

  • False, since the venv isn't active
  • An error that says to activate it first
  • None
  • True

Answer: True. The venv's own python is in the venv whether or not the venv is active: its sys.prefix is the venv's folder, and sys.base_prefix the Python the venv was made from.

pkg-a needs shared==1.0 and pkg-b needs shared==2.0. You run pip install pkg-a, then pip install pkg-b. What happens?

  • pip refuses to install pkg-b
  • pip installs pkg-b next to both versions of shared
  • pip installs pkg-b and shared 2.0, prints an ERROR about pkg-a, and ends with Successfully installed
  • pip uninstalls pkg-a

Answer: pip installs pkg-b and shared 2.0, prints an ERROR about pkg-a, and ends with Successfully installed. pip works out versions only for what it's installing now. It replaces shared 1.0, says that pkg-a no longer has the version it needs, and finishes; pip check finds the conflict afterwards.

Continue this course

Frequently asked questions

Should the folder be called .venv or venv?

Either works; the commands are the same with the name changed. Python's tutorial suggests .venv: the dot keeps the folder hidden in most shells, and the name can't clash with a .env file, which some tools read settings from.

Does a script run on a schedule, or in Docker, need the venv activated?

No. Run the venv's own Python by its path: .venv/bin/python on macOS and Linux, or the python.exe in the venv's Scripts folder on Windows. Python's documentation says a venv needn't be activated, and that commands installed into it run with its Python without that.

Why does pip say Requirement already satisfied?

The package is installed already, at a version the request allows, so pip leaves it alone. Python's guide to installing says an upgrade has to be asked for: python -m pip install --upgrade packaging.

What does --system-site-packages do?

python -m venv --system-site-packages .venv makes a venv that can also import the packages installed in the Python it was made from, and its pyvenv.cfg then says include-system-site-packages = true. venv's help puts it as "Give the virtual environment access to the system site-packages dir."

Does activating a venv clear PYTHONPATH?

No. Python's tutorial notes that an activated venv "does not alter the PYTHONPATH variable in any way", so the folders PYTHONPATH names are still searched for imports, as Module & Package Architecture for Large Codebases describes for a src folder.

What about uv, Poetry, pipx and conda?

They're separate tools for the same jobs. uv's help lists commands to create a virtual environment, keep a project's lockfile and install the commands that Python packages provide; Poetry keeps a project's dependencies in pyproject.toml and locks them in a poetry.lock file; pipx installs an application into a virtual environment it manages for you, which Ubuntu's externally-managed message suggests for applications; and conda is the package manager of the Anaconda distribution. Everything in this lesson works with Python and pip alone.

Can this site's editor install packages?

No: it has no pip and no terminal, and venv isn't part of its Python. It loads some libraries when a program imports them, packaging among them, which is why this lesson's examples run here.

Should a library pin its dependencies too?

Not with ==. A library gets installed next to other packages, and two exact pins of the same package can't both be met, as pkg-a and pkg-b showed. So a library states the ranges it works with in its pyproject.toml, and an application pins its whole environment in a requirements file. Packaging & Publishing Python Libraries to PyPI covers the library's side.

Related lessons