Created
November 12, 2025 11:06
-
-
Save mypy-play/5984d37d3c191f8db27c73b890d65f8f to your computer and use it in GitHub Desktop.
Shared via mypy Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from dataclasses import dataclass | |
| from typing import TypeVar, Generic, Callable, Dict, Any | |
| import sys | |
| T_Input = TypeVar("T_Input") | |
| class _RegisteredType(Generic[T_Input]): | |
| def __init__(self, name: str): | |
| self.name = name | |
| @dataclass | |
| class Request(Generic[T_Input]): | |
| r_type: _RegisteredType[T_Input] | |
| state: T_Input | |
| class C: | |
| def __init__(self): | |
| self._r_types: Dict[str, Callable[[Any], Any]] = {} | |
| def create_request_type(self, r_type: str, f: Callable[[Request[T_Input]], Any]) -> _RegisteredType[T_Input]: | |
| self._r_types[r_type] = f | |
| return _RegisteredType(r_type) | |
| def send_request(self, request: Request[Any]) -> Any: | |
| r_type = request.r_type.name | |
| f_to_call = self._r_types[r_type] | |
| return f_to_call(request) | |
| # --- Example --- | |
| def int_request_handler(req: Request[int]) -> str: | |
| return f"Handling int inside request: {req.state}" | |
| c = C() | |
| int_type = c.create_request_type("INT_OP", int_request_handler) | |
| # Works | |
| req1 = Request(r_type=int_type, state=42) | |
| c.send_request(req1) | |
| # Must fail | |
| req_fail = Request(r_type=int_type, state="wrong") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment