How to Type Check a Mock with pyright in Python
Shows how pyright validates a mock function against a TypedDict and Callable signature before runtime.
Python code
19 linesfrom typing import TypedDict, Callable
class User(TypedDict):
id: int
name: str
def get_user_name(user_id: int, get_user: Callable[[int], User]) -> str:
user = get_user(user_id)
return user["name"]
def mock_get_user(user_id: int) -> User:
return {"id": user_id, "name": f"User {user_id}"}
if __name__ == "__main__":
print(get_user_name(42, mock_get_user))
Output
User 42
How it works
The Callable type hint expects a function that takes an int and returns a User TypedDict. The mock function mock_get_user matches this signature, so pyright checks it without errors. When you run the script, it prints the name from the mock, demonstrating that the type contract is satisfied. This pattern ensures mocks align with the real interface early, catching mismatches before runtime failures.
Common mistakes
- Forgetting to import TypedDict and Callable from typing
- Mismatching the mock's parameter or return types vs the Callable definition
- Using a plain dict instead of the TypedDict structure, causing pyright errors
Variations
- Use `Protocol` to define a structural interface instead of Callable
- Use a unittest.mock.Mock with type hints for more complex mocks
Real-world use cases
- Type-checking mock HTTP clients in unit tests to match a service interface.
- Validating mock database repositories against a repository protocol in app code.
- Ensuring lambda or partial functions passed as callbacks meet expected signatures.
Sponsored
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.