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.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 15 views 0 copies

Python code

19 lines
Python 3.9+
from 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

stdout
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

  1. Use `Protocol` to define a structural interface instead of Callable
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.