How do you install a specific version of a Python package using pip? | A1Lab@MZeeshanM to PythonEnglish • 7 days ago

How do you install a specific version of a Python package using pip?

message-square
0

Use the double-equals operator == (pip install package_name==version) to install an exact version of a Python package, or use version comparison specifiers (>=, <, ~=) wrapped in quotes to install within a controlled version range.

Basic Example

# 1. Install an exact version of a package
pip install requests==2.31.0

# 2. Recommended: invoke pip through your active Python interpreter
python -m pip install requests==2.31.0

# 3. Install multiple pinned packages at once
pip install "numpy==1.26.4" "pandas==2.2.1"

Key Details & Version Specifiers

  • Always quote range operators in your shell: Characters like < and > are interpreted by Bash, Zsh, PowerShell, and Command Prompt as file redirection operators. Wrap specifiers in double quotes (e.g., pip install "django>=4.2,<5.0") so the shell passes them directly to pip.
  • Compatible release operator (~=): Using pip install "flask~=3.0.2" installs the latest patch release in the 3.0.x series (>=3.0.2, ==3.0.*) without jumping to 3.1.0—ideal for receiving bug and security fixes without breaking changes.
  • Downgrading an already-installed package: Running pip install requests==2.28.0 when 2.31.0 is already installed automatically uninstalls the newer version and installs 2.28.0—no --force-reinstall flag is required unless the target version is already installed and corrupted.
  • Checking available versions before installing: Run pip index versions <package_name> (available in pip 21.2+) to list all available versions on PyPI directly from your terminal:
    pip index versions requests
    
  • Pinning versions in requirements.txt: Record exact installed versions for reproducible builds using pip freeze > requirements.txt, then install them elsewhere with pip install -r requirements.txt.

Common pip Version Specifiers

Specifier Example Meaning Best Used When
== requests==2.31.0 Exact version match only Production requirements.txt files requiring strict reproducibility.
~= requests~=2.31.0 Compatible release (>=2.31.0, ==2.31.*) Allowing safe patch updates while locking minor/major versions.
>= / <= "requests>=2.28,<3.0" Bounded minimum and maximum version range Reusable libraries supporting multiple compatible releases.
!= "requests>=2.28,!=2.30.0" Excludes a specific broken or buggy release Skipping a known yanked or regression release.