Typing stubs for psutil
The `types-psutil` package provides PEP 561-compliant typing stubs for the `psutil` library, enabling static type checkers like MyPy and Pyright to analyze code that uses `psutil` for system and process utilities. As part of the typeshed project, its release cadence is tied to typeshed's updates and the `psutil` library's own releases, ensuring up-to-date type coverage. The current version is 7.2.2.20260408.
Warnings
- gotcha The `types-psutil` library provides type hints for the `psutil` library but does not install `psutil` itself. For your code to run and for type checking to be effective, `psutil` must also be explicitly installed in your environment.
- gotcha As `types-psutil` is part of `typeshed`, its versioning includes a date component (e.g., `7.2.2.20260408`). While it generally tracks the `psutil` version it provides stubs for, it's possible for there to be a mismatch. Ensure the `psutil` version you are using is compatible with the installed `types-psutil` stubs to avoid partial or incorrect type coverage, especially with very new `psutil` releases.
- gotcha Typing stubs like `types-psutil` are purely for static analysis tools (e.g., MyPy, Pyright). They do not add any runtime functionality or modify the behavior of `psutil`. Do not attempt to import symbols directly from `types_psutil` or expect it to change runtime behavior; it only influences how type checkers interpret your `psutil` usage.
Install
-
pip install types-psutil
Imports
- No direct imports from types-psutil
Users import symbols from `psutil` (e.g., `from psutil import cpu_percent`) after installing `types-psutil` for type checking.
Quickstart
import psutil
from typing import Dict, Any
def get_process_info(pid: int) -> Dict[str, Any]:
"""Gets basic info for a process by PID."""
try:
process = psutil.Process(pid)
return {
"pid": process.pid,
"name": process.name(),
"cpu_percent": process.cpu_percent(interval=0.1),
"memory_info_mb": process.memory_info().rss / (1024 * 1024) # MB
}
except psutil.NoSuchProcess:
return {"error": f"Process {pid} not found."}
except psutil.AccessDenied:
return {"error": f"Access denied for process {pid}."}
if __name__ == "__main__":
# Get info for current process
current_process_info = get_process_info(psutil.Process().pid)
print(f"Current process info: {current_process_info}")
# To leverage `types-psutil`, install it and run a type checker:
# pip install psutil types-psutil mypy
# mypy your_script.py
# MyPy will then correctly infer types for `process.name()`, `process.cpu_percent()`, etc.