Skip to content

importpatch

Post-import hooks that a package registers just by being installed. A distribution declares "when requests is imported, call mypkg.hooks.patch" as an entry point, and every program in that environment gets the patch the moment it imports requests. A hook that fails is logged and skipped; it never breaks the import it patches.

Installation

pip install importpatch

There are no extras. The wheel installs importpatch.pth, which activates the hook in every interpreter of the environment; IMPORTPATCH_DISABLE=1 turns it off.

30-second tour

Declare the hook in your package's pyproject.toml:

[project.entry-points.importpatch]
requests = "mypkg.hooks.patch_requests"

patch_requests(module) is called with the requests module right after it is imported. In a running program, without packaging:

import importpatch

importpatch.add("json", "mypkg.hooks.patch_json")  # runs at once if json is loaded

A patcher naming a module, rather than a function, is called through that module's importpatch(name, module). Hooks not provided by a package go in pyimportpatch.cfg (system-wide in /etc or %PROGRAMDATA%, per user in the platform configuration directory): a [json] section, then mypkg.hooks.patch_json on its own line. patcher = false switches a hook off, an installed package's included.

Learn more