Sub topic 6
Pinning and constraining versions
This chapter assumes you can create and activate a virtual environment and run python -m pip install inside it. You should also know that a package has a name and a version number such as 2.32.3. Here you learn to say which versions of a package your project accepts.
Why version specifiers exist
A command such as python -m pip install requests installs the newest release that pip can find. That is fine on the day you run it. Months later, a fresh install may pull a release with a changed or removed feature, and code that worked yesterday fails.
A version specifier is a rule that limits which releases pip may choose. The rules come from PEP 440, the standard that defines Python version numbers and how to compare them. You write the rule right after the package name.
There are two common strategies:
- Pinning fixes one exact version, such as
requests==2.32.3. Installs are predictable, but you receive no bug or security fixes until you change the pin. - Constraining allows a range, such as
requests>=2.31,<3. You receive compatible fixes, but two installs made at different times can differ.
Applications usually pin, because the team controls where the code runs. Libraries usually constrain, because pinning an exact version in a library forces that choice on every project that uses it.
The comparison operators
The table lists the operators you will use most.
| Specifier | Meaning | Example match |
|---|---|---|
| `==2.31.0` | Exactly this version | `2.31.0` |
| `!=2.30.0` | Anything except this version | `2.31.0` |
| `>=2.31` | This version or newer | `2.31`, `3.0` |
| `<3` | Older than this version | `2.99` |
| `>2.31` | Strictly newer | `2.31.1` |
| `<=2.32` | This version or older | `2.32` |
| `~=2.31` | Compatible release | `2.31`, `2.40` |
| `==2.31.*` | Any release in the 2.31 series | `2.31.9` |
The === operator also exists. It compares the version as a plain string and is meant for unusual, non-standard version names. You will rarely need it.
Combining specifiers
A comma means "and". Every part must be true for pip to accept a release:
requests>=2.31,<3This accepts 2.31.0, 2.32.3, and 2.99, but rejects 2.30.0 and 3.0. The comma never means "or". If you need to skip a bad release, add an exclusion:
requests>=2.31,<3,!=2.32.0Quote specifiers on the command line
Characters such as > and < are redirection operators in most shells. Without quotes, the shell treats >=2.31 as "write output to a file named =2.31". Quote the whole requirement:
python -m pip install "requests>=2.31,<3"
python -m pip install "requests~=2.31"
python -m pip install "requests==2.31.*"Inside a requirements file, no quotes are needed, because pip reads the file directly and no shell is involved.
Compatible release with ~=
The ~= operator is shorthand for "this version or newer, but not the next level up". How it expands depends on how many parts you write:
~=2.31means>=2.31, ==2.*. This allows2.40but not3.0.~=2.31.1means>=2.31.1, ==2.31.*. This allows2.31.9but not2.32.0.
The rule is that the last part you write is the one allowed to grow. Because the operator needs at least two parts, ~=2 is invalid.
The operator is only as reliable as the package's own versioning. It assumes the project avoids breaking changes in minor releases. Many projects follow that convention, and some do not. Check a project's release notes before you trust it.
Version numbers are not decimals
Versions are compared part by part as integers, not as decimal numbers. So 2.9 is older than 2.10, because 9 is less than 10. Trailing zeros are ignored, so 2.31 and 2.31.0 are the same version. This also means ==2.31 matches 2.31.0.
You can check how a rule behaves with the packaging library, which pip itself builds on. Install it first with python -m pip install packaging, then run:
from packaging.specifiers import SpecifierSet
from packaging.version import Version
rule = SpecifierSet(">=2.31,<3")
for text in ["2.30.0", "2.31", "2.32.3", "3.0.0"]:
print(text, rule.contains(text))
print(Version("2.9") < Version("2.10"))
print(Version("2.31") == Version("2.31.0"))
print(SpecifierSet("~=2.31").contains("2.40.0"))
print(SpecifierSet("~=2.31.1").contains("2.32.0"))The output is False, True, True, False for the four versions, followed by True, True, True, False for the last four lines. Testing a rule this way costs nothing and is safer than discovering a mismatch during a deployment.
Pre-releases are skipped by default
Releases such as 2.32.0rc1 (a release candidate), 2.32.0b2 (beta), or 2.32.0.dev3 (development) are pre-releases. By default, pip ignores them unless one of these is true:
- You pass
--preto pip. - A specifier names a pre-release explicitly, such as
requests==2.32.0rc1. - The pre-release is the only version that satisfies the requirements.
from packaging.specifiers import SpecifierSet
rule = SpecifierSet(">=2.31,<3")
print(rule.contains("2.32.0rc1"))
print(rule.contains("2.32.0rc1", prereleases=True))The first line prints False and the second prints True. This default protects you from picking up unstable code by accident.
Environment markers
A requirement can apply only in some situations. You add a condition after a semicolon. This condition is called an environment marker:
tomli>=2.0; python_version < "3.11"
colorama>=0.4; sys_platform == "win32"The first line installs tomli only on Python versions older than 3.11. The second installs colorama only on Windows. Markers are useful when one requirements file must serve several platforms.
Seeing what pip will do before it does it
The --dry-run option makes pip resolve the requirements and report what it would install, without changing the environment:
python -m pip install --dry-run "requests>=2.31,<3"Use it when you edit a specifier and want to see the effect first. Combine it with python -m pip list to compare the result with what is already installed.
When specifiers conflict
Your project is rarely the only thing placing rules on a package. Each package you install has its own dependencies, and those carry specifiers too. pip's resolver must find one version of every package that satisfies all the rules at once.
Suppose your project needs urllib3>=2.2, while another package you installed needs urllib3<2. No version satisfies both. pip stops with an error that includes the text ResolutionImpossible and lists the conflicting requirements. Read that list, because it names the packages that disagree.
Typical fixes, in order of preference:
- Loosen your own specifier if it is tighter than it needs to be.
- Upgrade or downgrade the other package to a release with compatible rules.
- Drop one of the packages if no compatible set exists.
After any install, run python -m pip check. It reports installed packages whose dependencies are missing or incompatible, which can happen if an earlier install used pip's older behavior or forced a version.
Choosing a specifier
A few guidelines follow from the diagram:
- Set a lower bound only when you need a feature or fix that appeared in that release. Do not set one just because it is the version you have installed.
- Set an upper bound at the next major version, such as
<3, when the package follows semantic versioning (major version changes signal breaking changes). - Use
!=for one known bad release instead of tightening the whole range. - Pin exactly in files that describe a deployable application, and keep ranges in the project's own declared dependencies.
Common mistakes
- Forgetting quotes.
pip install requests>=2creates a file named=2and installs the newestrequests. Quote the requirement. - Writing
=instead of==. A single equals sign is not a valid operator. pip reports an invalid requirement. - Expecting a comma to mean "or". It always means "and".
- Using
==2.31.*with a single-version mindset. The wildcard matches the whole 2.31 series. Use it only with==or!=, because>=2.31.*is invalid. - Pinning transitive dependencies by hand. The packages that your packages depend on are easy to forget. Recording the whole installed set is the job of a requirements file, which the next chapters cover.
Exercises
Exercise
What does ~=2.31.1 allow, and what does ~=2.31 allow? Give one version that the first rejects but the second accepts.
Show answer
~=2.31.1 means >=2.31.1, ==2.31.*, so it allows 2.31.1 through 2.31.x only. ~=2.31 means >=2.31, ==2.*, so it allows any 2.x release from 2.31 up. The version 2.32.0 is rejected by the first and accepted by the second.
Exercise
You run python -m pip install requests>=2.31,<3 in a shell and no requests install matches your intent. What happens, and how do you fix the command?
Show answer
The shell reads > and < as redirection operators. It writes output to a file named =2.31, or tries to read from a file, and pip receives only requests or an incomplete command. Quote the requirement: python -m pip install "requests>=2.31,<3".
Exercise
A library you maintain needs requests 2.31 or newer, works with every 2.x release, and is broken by release 2.32.0. Write one specifier line for its dependency list.
Show answer
requests>=2.31,<3,!=2.32.0. The lower bound sets the first working release, <3 blocks the next major version, and !=2.32.0 excludes the single bad release.