Typing Stubs for pkg_resources
This library provides static type checking stubs for the `pkg_resources` module, which is primarily distributed as part of `setuptools`. It enables type checkers like MyPy and pyright to analyze code using `pkg_resources` for package metadata and resource management. While `pkg_resources` itself is considered a legacy API, these stubs are actively maintained as part of the `typeshed` project to support existing Python codebases. New versions are released periodically as stub definitions are updated or improved.
Warnings
- gotcha The `pkg_resources` module, for which these stubs are provided, is considered a legacy API. For new Python projects (especially Python 3.8+), it's highly recommended to use `importlib.metadata` for package metadata access. For older Python versions, `setuptools.metadata` offers a more modern alternative within the setuptools ecosystem.
- gotcha Type stubs (`types-pkg-resources`) do not provide any runtime functionality. They are solely for static analysis by type checkers. Your project must have the actual `pkg_resources` module (typically bundled with `setuptools`) installed to run the code at runtime.
- gotcha The version of `types-pkg-resources` tracks the evolution of the *stub definitions* for `pkg_resources`, not the `pkg_resources` module's actual version or functionality. The `pkg_resources` module's behavior is tied to the `setuptools` library version it's shipped with.
Install
-
pip install types-pkg-resources -
pip install types-pkg-resources setuptools
Imports
- pkg_resources
import pkg_resources
- Distribution
from pkg_resources import Distribution
Quickstart
import pkg_resources
from typing import List
# Example function using pkg_resources to list installed packages
def get_installed_package_names() -> List[str]:
"""Returns a sorted list of project names for installed packages."""
# pkg_resources.working_set provides access to the active distributions
distributions = pkg_resources.working_set
return sorted([d.project_name for d in distributions])
if __name__ == "__main__":
print("--- Listing installed packages via pkg_resources ---")
packages = get_installed_package_names()
print(f"Found {len(packages)} packages. First 5:")
for p in packages[:5]:
print(f"- {p}")
# To type-check this code:
# 1. Install necessary packages: `pip install types-pkg-resources setuptools mypy`
# 2. Run mypy: `mypy your_script_name.py`