Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

I'm trying to make a system where the arguments that are passed to an RPC are specified via type hints, then at runtime a backend checks the RPC can fulfil the requested spec and creates a concrete object with the given signature.

Doing this for positional arguments seems to be fine:

from collections.abc import Callable
from typing import Generic, ParamSpec, Protocol, TypeVar

P = ParamSpec("P")
T = TypeVar("T")

class RPC(Generic[P, T]):
    def server(self) -> str: ...
    async def do_rpc(self, *args: P.args, **kwargs: P.kwargs) -> T: ...

class FirstAPIAttempt:
    my_rpc: RPC[[int, str], float]
    my_other_rpc: RPC[[float], float]

However, I would like to specify that the RPC takes keyword arguments. I can see that pyright can infer keyword arguments of a function:

class FunctionBox(Generic[P, T]):
    def __init__(self, func: Callable[P, T]):
        self.func = func

def f(x: int, y: str) -> float: ...

fb = FunctionBox(f)
reveal_type(fb) # fb: FunctionBox[(x: int, y: str), float]

But that would be a SyntaxError:

class SecondAPIAttempt:
    my_rpc: RPC[(x: int, y: str), float]
    my_other_rpc: RPC[(z: float), float]

I wondered about using a protocol:

class MyRPCSpec(Protocol):
    async def __call__(self, x: int, y: str) -> float: ...

class ThirdAPIAttempt:
    my_rpc: RPC[MyRPCSpec]

But as RPC is generic on P and T then I can't do RPC[MyRPCSpec] and I can't work out how I would get P or T out of MyRPCSpec...

You must be logged in to vote

Replies: 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
🙏
Q&A
Labels
None yet
1 participant
Morty Proxy This is a proxified and sanitized view of the page, visit original site.