Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created January 22, 2026 14:43
Show Gist options
  • Select an option

  • Save mypy-play/7f83d284572c0bcd986945d87f85f668 to your computer and use it in GitHub Desktop.

Select an option

Save mypy-play/7f83d284572c0bcd986945d87f85f668 to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from __future__ import annotations
from dataclasses import dataclass
from typing import Protocol
# --- "generated" RPC types (pretend these come from codegen) ---
@dataclass(frozen=True)
class HelloRequest:
name: str
@dataclass(frozen=True)
class HelloReply:
message: str
class HelloWorldService(Protocol):
"""
Go-style interface: any user implementation that matches this method
signature satisfies the service contract. No inheritance required.
"""
def SayHello(self, request: HelloRequest) -> HelloReply:
...
# --- framework code that "registers" the user's service implementation ---
def register_hello_world_service(service: HelloWorldService) -> None:
# In a real RPC framework, this would store `service` in a server/router.
# We'll just exercise it to prove both runtime + mypy behavior.
demo_req = HelloRequest(name="Jacob")
demo_res = service.SayHello(demo_req)
print(f"[server] got reply: {demo_res.message}")
# --- user code: they implement the stub by matching the Protocol ---
class MyHelloWorldImpl:
# Note: NO inheritance from HelloWorldService.
def SayHello(self, request: str) -> HelloReply:
return HelloReply(message=f"Hello, {request.name}!")
# --- run ---
if __name__ == "__main__":
register_hello_world_service(MyHelloWorldImpl())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment