Typing Stubs for the Mock Library
This package provides high-quality type stubs for the `mock` library (and by extension, `unittest.mock` from the standard library), enabling static type checkers like `mypy` to understand and validate usage of mock objects. Part of the `typeshed` project, it is actively maintained with a continuous release cadence reflecting updates to the stubs. The current version is 5.2.0.20260408.
Warnings
- gotcha Do not import symbols directly from `types_mock`. This package provides type stubs for static analysis (e.g., by `mypy`), not runtime code. You should import `Mock`, `patch`, etc., from `unittest.mock` (or the `mock` backport library).
- gotcha `types-mock` is solely for static type checking; installing it has no effect on your program's runtime behavior. It's a development dependency, typically used with tools like `mypy`.
- gotcha There are two main 'mock' libraries: the built-in `unittest.mock` (Python 3.3+) and the standalone `mock` backport for older Python versions. `types-mock` provides stubs for both, but ensure you are consistent in which library you are using in your project's runtime code.
- gotcha The version number of `types-mock` (e.g., `5.2.0.20260408`) does not correspond to a specific version of the `mock` runtime library. Instead, it reflects the version of the stubs within the `typeshed` project and the date they were published.
Install
-
pip install types-mock
Imports
- Mock
from unittest.mock import Mock
- patch
from unittest.mock import patch
Quickstart
import sys
from unittest.mock import Mock, MagicMock
# Define a simple service with type hints
class MyService:
def fetch_data(self, url: str) -> dict:
return {"status": "ok", "url": url, "data": "real content"}
def process_data(service: MyService, target_url: str) -> str:
data = service.fetch_data(target_url)
if data and data.get("status") == "ok":
return f"Successfully processed data from {data.get('url')}"
return "Failed to process data"
# --- Usage with types-mock (implicitly through mypy) ---
# 1. Mocking a method explicitly typed
mock_service_typed: MyService = Mock(spec=MyService) # Use spec for stricter type checking
mock_service_typed.fetch_data.return_value = {"status": "ok", "url": "mocked.com", "data": "mocked content"}
print(f"Typed Mock Result: {process_data(mock_service_typed, 'http://example.com')}")
# mypy would catch this if uncommented because 123 is not a string for url:
# print(process_data(mock_service_typed, 123))
# 2. MagicMock is also typed
magic_mock_example: MagicMock = MagicMock()
magic_mock_example.__len__.return_value = 5
print(f"MagicMock length: {len(magic_mock_example)}")
# To see types-mock in action, save this as `app.py`, then run:
# pip install mypy
# mypy app.py