meta_package_manager.managers.pip module¶

class meta_package_manager.managers.pip.Pip[source]¶

Bases: PackageManager

The pip package installer for Python, driven as a module (python -m pip) rather than through the pip executable.

Calling the module through the interpreter lets pip upgrade itself, an advantage on Windows in particular: see why you should use python -m pip.

Installed and outdated packages are read from pip’s list --format=json output. The outdated query adds --not-required to report only top-level packages, since upgrading a transitive dependency can break its parent’s version constraints (#1214).

Note

All operations target the default pip scope (system site-packages, or the active virtualenv). Per-scope targeting (system vs user vs venv) and multi-binary discovery (multiple pythons via pyenv) are tracked in #1725.

Note

Interpreter discovery probes the running Python first, so an mpm installed inside a virtualenv manages that virtualenv, then the Python(s) on PATH. Three kinds are skipped so the manager only targets a scope the user can install into: mpm’s own distributor-managed bundle (Homebrew stages it under a Cellar prefix), any externally-managed, non-virtualenv interpreter that PEP 668 forbids pip install into, and any interpreter carrying no pip to drive. When every candidate is skipped, the manager reports as unavailable.

Note

Installs, upgrades and removals are marked privileged, so a global install can escalate with --sudo, but escalation is off by default. The supply-chain cooldown needs pip 26.1, the first release to honor --uploaded-prior-to; older pip silently ignores the release-age gate.

Initialize cli_errors list.

operation_notes: ClassVar = {'search': 'PyPI disabled its server-side search API in 2020 ([pypa/pip#5216](https://github.com/pypa/pip/issues/5216#issuecomment-744605466)), so `pip search` no longer works.'}¶

Per-operation hints rendered in the Notes column of the manager page’s Operations table.

Keyed by the Operations member name, each value is a single short sentence explaining why the manager lacks the operation, or what makes its implementation partial: the pointer a reader needs to judge whether the gap is one they could help close. Each sentence starts with a capital and closes with a period, and starts on a word rather than a code span, so the cell reads standalone beside its row. A blank cell stays silent: a manager documenting nothing documents no gap.

The full rationale never lives here: it belongs in a comment beside the implementing method (or beside this declaration, for an operation with no method to hang it on), so the sentence on the page stays a hint and the code keeps the story. The class docstring follows the same split: it keeps only what a user needs to run the tool day to day, never how mpm wraps it.

Validated by test_operation_notes, which also checks every key matches a real operation: a key outside the enum’s vocabulary would never reach a page.

name: str = 'Python pip'¶

Return package manager’s common name.

Default value is based on class name.

homepage_url: str | None = 'https://pip.pypa.io'¶

Home page of the project, only used in documentation for reference.

Left unset when the home page is the project’s repository, which repository_url names on its own, and when it is the project’s manual, which documentation_url names. Never inherited, like the other links.

documentation_url: str | None = 'https://pip.pypa.io/en/stable/cli/'¶

Entry point of the project’s own documentation, or None when it has none.

The manual, the documentation site, or the man page of the CLI mpm drives: whichever page a user reads to learn the commands this manager wraps. Listed between homepage_url and repository_url in the links of the manager’s page, so a reader reaching for the tool’s reference finds it in the box of facts rather than in the prose below it.

Left unset where a link would state a fact twice or invent one: a tool documenting itself in its repository alone, whose README repository_url already reaches. A page about the ecosystem rather than the tool does not qualify either.

Where a project’s only site is its manual, that address belongs here and homepage_url stays unset: the slot names what the page is, and a reader reaching for the reference looks under the documentation link.

Never inherited, like every other link: the AUR helpers extending pacman each document themselves.

repository_url: str | None = 'https://github.com/pypa/pip'¶

Repository holding the project’s code, or None when it has no public one.

Linked from the manager’s documentation page. Also what the weekly metrics sample reads: docs/docs_update.py writes it into the [tool.repomatic.metrics] subjects of pyproject.toml when its forge answers the sampler, through a mirror for a forge that does not.

Never inherited, for the same reason as wikipedia_url: the AUR helpers extending pacman each live in a repository of their own.

wikipedia_url: str | None = 'https://en.wikipedia.org/wiki/Pip_(package_manager)'¶

English Wikipedia article about the project, or None when it has none.

Listed last in the links of the manager’s documentation page. The article covers the project that home page names, or is a redirect Wikipedia keeps under the project’s name, landing on the part of a broader article that describes it: Cargo_(software) opens the Cargo section of the Rust article. An article that merely mentions the project does not count, nor does one about a related subject: lazy is a Neovim plugin manager, and the Neovim article is not about it.

Never inherited: the metaclass resets it to None on any class not declaring its own. A subclass often wraps a distinct project, like the six AUR helpers extending pacman, and would otherwise present pacman’s article as its own. Documentation-only, like homepage_url.

Slug of the brand mark standing for this manager in the documentation.

Names an SVG vendored under docs/assets/managers/, whose provenance and license are recorded in docs/assets/managers/logos.yaml. Inlined at the top of the manager’s page by meta_package_manager._docs; a manager leaving it unset keeps the page’s default package glyph.

Several managers legitimately share one slug, either because they wrap the same upstream (brew and cask) or because the tool has no mark of its own and its ecosystem’s stands in (apt under Debian’s swirl, cargo under Rust’s gear). Documentation-only, like homepage_url: no CLI output reads it.

keywords: tuple[str, ...] = ('pypi',)¶

Well-known names for this manager that its id does not already carry.

Merged into the PyPI keywords of pyproject.toml by update_keywords() of docs/docs_update.py, alongside every manager ID and the globally curated KEYWORDS_EXTRAS. Declare an alias here rather than in that tuple whenever it names this manager: an alias living beside the class it describes cannot outlive it, where a central entry silently rots once the manager is renamed or dropped.

Reserve KEYWORDS_EXTRAS for terms belonging to no manager in particular, like cyclonedx or package manager. Documentation-only: no CLI output reads it.

Each keyword also becomes a content rule of the issue labeller, so its precision bar applies here: see generate_content_rules(). A subclass inherits the terms of its parent without claiming them, since test_manager_keywords_have_one_owner reads what a class declares itself.

platforms: frozenset[Platform] | Group | Platform | Iterable[Platform | Group] = frozenset({Platform(id='aix', name='IBM AIX'), Platform(id='almalinux', name='AlmaLinux'), Platform(id='alpine', name='Alpine Linux'), Platform(id='altlinux', name='ALT Linux'), Platform(id='amzn', name='Amazon Linux'), Platform(id='android', name='Android'), Platform(id='arch', name='Arch Linux'), Platform(id='buildroot', name='Buildroot'), Platform(id='cachyos', name='CachyOS'), Platform(id='centos', name='CentOS'), Platform(id='chromeos', name='ChromeOS'), Platform(id='clearlinux', name='Clear Linux OS'), Platform(id='cloudlinux', name='CloudLinux OS'), Platform(id='crux', name='CRUX'), Platform(id='cygwin', name='Cygwin'), Platform(id='debian', name='Debian'), Platform(id='dragonfly_bsd', name='DragonFly BSD'), Platform(id='endeavouros', name='EndeavourOS'), Platform(id='exherbo', name='Exherbo Linux'), Platform(id='fedora', name='Fedora'), Platform(id='freebsd', name='FreeBSD'), Platform(id='generic_linux', name='Generic Linux'), Platform(id='gentoo', name='Gentoo Linux'), Platform(id='guix', name='Guix System'), Platform(id='haiku', name='Haiku'), Platform(id='hurd', name='GNU/Hurd'), Platform(id='ibm_powerkvm', name='IBM PowerKVM'), Platform(id='illumos', name='illumos'), Platform(id='kali', name='Kali Linux'), Platform(id='kvmibm', name='KVM for IBM z Systems'), Platform(id='linuxmint', name='Linux Mint'), Platform(id='macos', name='macOS'), Platform(id='mageia', name='Mageia'), Platform(id='mandriva', name='Mandriva Linux'), Platform(id='manjaro', name='Manjaro Linux'), Platform(id='midnightbsd', name='MidnightBSD'), Platform(id='netbsd', name='NetBSD'), Platform(id='nixos', name='NixOS'), Platform(id='nobara', name='Nobara'), Platform(id='nutyx', name='NuTyX'), Platform(id='openbsd', name='OpenBSD'), Platform(id='opensuse', name='openSUSE'), Platform(id='openwrt', name='OpenWrt'), Platform(id='oracle', name='Oracle Linux'), Platform(id='os400', name='IBM i'), Platform(id='parallels', name='Parallels'), Platform(id='pidora', name='Pidora'), Platform(id='pikaos', name='PikaOS'), Platform(id='raspbian', name='Raspbian'), Platform(id='rhel', name='RedHat Enterprise Linux'), Platform(id='rocky', name='Rocky Linux'), Platform(id='scientific', name='Scientific Linux'), Platform(id='slackware', name='Slackware'), Platform(id='sles', name='SUSE Linux Enterprise Server'), Platform(id='slitaz', name='SliTaz GNU/Linux'), Platform(id='solaris', name='Solaris'), Platform(id='solus', name='Solus'), Platform(id='sourcemage', name='Source Mage GNU/Linux'), Platform(id='sunos', name='SunOS'), Platform(id='tuxedo', name='Tuxedo OS'), Platform(id='ubuntu', name='Ubuntu'), Platform(id='ultramarine', name='Ultramarine'), Platform(id='void', name='Void Linux'), Platform(id='windows', name='Windows'), Platform(id='wsl1', name='Windows Subsystem for Linux v1'), Platform(id='wsl2', name='Windows Subsystem for Linux v2'), Platform(id='xenserver', name='XenServer')})¶

List of platforms supported by the manager.

Allows for a mishmash of platforms and groups of platforms. Will be normalized into a frozenset of Platform instances at instantiation.

privileged_operations: ClassVar[frozenset[str]] = frozenset({'install', 'remove', 'upgrade'})¶

Operations with at least one command this manager marks privileged.

Keyed by the Operations member name, like operation_notes. An operation belongs here when a method implementing it passes sudo=True to run_cli() or build_cli(), with the method-to-operation map of METHOD_OPERATIONS. Those commands are the only ones the escalation policy (sudo, else default_sudo) wraps in the escalator. A definition derives the set from the operations it marks sudo = true.

prime_sudo() reads it to prompt only for the managers that escalate a command of the current run. With [mpm.overrides.gem] sudo = true, mpm sync asks for no password: the gem sources --update command of sync carries no marker. test_privileged_operations holds the set to the markers in the method bodies.

requirement: str | None = '>=26.1.0'¶

26.1 is the first version to ship --uploaded-prior-to, the release-age gate mpm uses for the supply-chain cooldown (see cooldown_env_var). Older pip releases silently ignore PIP_UPLOADED_PRIOR_TO, so the floor avoids advertising a gate that does nothing.

cooldown_env_var: ClassVar[str | None] = 'PIP_UPLOADED_PRIOR_TO'¶

pip honors a release-age cooldown through its --uploaded-prior-to resolver option.

pip maps any PIP_<UPPER_SNAKE> environment variable to a config setting, so PIP_UPLOADED_PRIOR_TO sets the option without touching the user’s pip.conf. The flag excludes from resolution any distribution uploaded after the given instant, which covers install and upgrade (with transitive dependencies). pip parses the RFC 3339 timestamp produced by the default meta_package_manager.execution.CLIExecutor.cooldown_env_value().

See pypa/pip#13674.

cli_names: tuple[str, ...] = ('python3', 'python')¶

List of CLI names the package manager is known as.

This list of recognized CLI names is ordered by priority. That way we can influence the search of the right binary.

..hint::

This was helpful in the case of the Python transition from 2.x to 3.x, where multiple versions of the same executable were named python or python3.

By default, this property’s value is derived from the manager’s ID (see the MetaPackageManager.__init__ method above).

pre_args: tuple[str, ...] = ('-m', 'pip', '--no-color')¶
version_cli_options: tuple[str, ...] = ('-m', 'pip', '--no-color', '--version')¶

CLI options used to produce the version of the package manager.

The raw output produced by the package manager CLI will be parsed with the version_regexes below to extract the version number.

version_regexes: tuple[str, ...] = ('pip\\s+(?P<version>\\S+)',)¶
$ python -m pip --no-color --version
pip 26.2.1 from /tmp/mpm-pip/lib/python3.14/site-packages/pip (python 3.14)
search_all_cli(cli_names, env=None)[source]¶

Yield the Python interpreters the pip manager may target.

The running interpreter is probed first, so an mpm installed into a virtualenv manages that virtualenv’s own packages, then the Python(s) found on PATH. Three kinds of interpreter are skipped, so the pip manager only ever targets a scope the user can actually install into:

  • mpm’s own distributor-managed bundle (see _running_from_bundled_app),

  • any externally-managed, non-virtualenv interpreter PEP 668 would forbid pip install into (see _pip_install_blocked), and

  • any interpreter carrying no pip at all (see _pip_module_missing).

When every candidate is skipped the manager is left with no cli_path and reports as unavailable, which is correct: there is no user-managed pip environment to act on.

Todo

Evaluate findpython (the maintained MIT rewrite of pythonfinder) to replace the discovery loop here. It would only cover discovery: the eligibility filters (_running_from_bundled_app, _pip_install_blocked, _pip_module_missing) stay mpm’s job, since findpython locates interpreters but judges neither whether one carries pip nor whether pip install is allowed into it.

Return type:

Generator[Path, None, None]

property version: TokenizedString | None[source]¶

Print Python’s own version before Pip’s.

This gives much more context to the user about the environment when a Python executable is found but Pip is not.

Runs:

$ python --version --version
Python 3.10.10 (Feb  8 2023, 05:34) [Clang 14.0.0 (clang-1400.0.29.202)]
property install_root: Path | None[source]¶

The site-packages directory of the python driving this pip.

Asked of the interpreter itself, so override_pre_args drops the -m pip plumbing every other operation rides:

$ python3 -c "import sysconfig; print(sysconfig.get_paths()['purelib'])"
/usr/lib/python3/dist-packages
property installed: Iterator[Package]¶

Fetch installed packages.

$ python -m pip --no-color list --format=json --verbose --quiet
[
 {
    "version": "1.3",
    "name": "backports.functools-lru-cache",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
  },
  {
    "version": "0.9999999",
    "name": "html5lib",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
  },
  {
    "name": "setuptools",
    "version": "46.0.0",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": ""
  },
  {
    "version": "2.8",
    "name": "Jinja2",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": ""
  }
]
package_metadata_batch(packages)[source]¶

Enrich installed pip packages via importlib.metadata.

Each installed distribution exposes its METADATA file (the Core Metadata from PEP 621) plus RECORD, WHEEL, and INSTALLER files in its .dist-info directory. This method reads them in-process: no shell-outs, no network, fast enough to enumerate hundreds of distributions in a fraction of a second.

Maps Home-page / Project-URL lines into the portable homepage / vcs_url / issue_tracker_url slots, walks Requires-Dist into typed meta_package_manager.package.Dependency edges, and promotes the upstream author or maintainer to meta_package_manager.package.Originator.

Return type:

Iterator[tuple[Package, PackageMetadata]]

id: str = 'pip'¶

Package manager’s ID.

Derived by defaults from the lower-cased class name in which underscores _ are replaced by dashes -.

This ID must be unique among all package manager definitions and lower-case, as they’re used as feature flags for the mpm CLI.

property outdated: Iterator[Package]¶

Fetch outdated packages.

Note

The --not-required flag filters out transitive dependencies, restricting results to top-level packages only. Upgrading transitive dependencies can break version constraints of their parent packages. See #1214.

$ python -m pip --no-color list --format=json --outdated         > --not-required --verbose --quiet
[
  {
    "latest_filetype": "wheel",
    "version": "0.7.9",
    "name": "alabaster",
    "latest_version": "0.7.10",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
  },
  {
    "latest_filetype": "wheel",
    "version": "0.9999999",
    "name": "html5lib",
    "latest_version": "0.999999999",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
   },
  {
    "latest_filetype": "wheel",
    "version": "2.8",
    "name": "Jinja2",
    "latest_version": "2.9.5",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
   },
  {
    "latest_filetype": "wheel",
    "version": "0.5.3",
    "name": "mccabe",
    "latest_version": "0.6.1",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
   },
  {
    "latest_filetype": "wheel",
    "version": "2.2.0",
    "name": "pycodestyle",
    "latest_version": "2.3.1",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": "pip"
   },
  {
    "latest_filetype": "wheel",
    "version": "2.1.3",
    "name": "Pygments",
    "latest_version": "2.2.0",
    "location": "/usr/local/lib/python3.7/site-packages",
    "installer": ""
   }
]
virtual: bool = False¶

Should we expose the package manager to the user?

Virtual package manager are just skeleton classes used to factorize code among managers of the same family.

install(package_id, version=None)[source]¶

Install one package.

$ python -m pip --no-color install arrow
Collecting arrow
  Using cached arrow-1.1.1-py3-none-any.whl (60 kB)
Collecting python-dateutil>=2.7.0
  Using cached python_dateutil-2.8.2-py2.py3-none-any.whl (247 kB)
Requirement already satisfied: six>=1.5 in python3.9/site-packages (1.16.0)
Installing collected packages: python-dateutil, arrow
Successfully installed arrow-1.1.1 python-dateutil-2.8.2
Return type:

str

upgrade_one_cli(package_id, version=None)[source]¶

Generates the CLI to upgrade the package provided as parameter.

$ python -m pip --no-color install --upgrade six
Collecting six
  Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
Installing collected packages: six
  Attempting uninstall: six
    Found existing installation: six 1.14.0
    Uninstalling six-1.14.0:
      Successfully uninstalled six-1.14.0
Successfully installed six-1.15.0
Return type:

tuple[str, ...]

Note

Pip lacks support of a proper full upgrade command. Raising an error let the parent class upgrade packages one by one.

See pypa/pip#59.

remove(package_id)[source]¶

Remove one package.

$ python -m pip --no-color uninstall --yes arrow
Return type:

str

cleanup_cache()[source]¶

Removes things we don’t need anymore.

$ python -m pip --no-color cache purge
Return type:

None

doctor_cli()[source]¶

Generates the CLI running the native self-diagnosis.

check verifies that installed packages have compatible dependencies, reporting conflicts on <stdout> and exiting non-zero on any.

$ python -m pip --no-color check
No broken requirements found.
Return type:

tuple[str, ...]