Skip to content

Type interference: ProtocolOf? #1944

@kai3341

Description

@kai3341

I'm looking the way to interfere existing types explicitly, like typeof / keyof in Typescript

I have 2 use cases:

  • existing function definition -> Callable[...]
  • dataclass __init__ signature / protocol

I think it should look like:

from typing import ProtocolOf

def foo(a: int, b: float) -> float:
    return a * b

FooProtocol = ProtocolOf[foo]

Should be equal to:

class FooProtocol(Protocol):
    def __call__(a: int, b: float) -> float: ...

Or dataclasses:

from dataclasses import dataclass
from typing import ProtocolOf

@dataclass()
class Foo:
    a: int
    b: float

Here I'm not sure which way is better

# way 1:
FooProtocol = ProtocolOf[Foo]

Should be equal to:

class FooProtocol(Protocol):
    def __call__(a: int, b: float) -> Foo: ...
# way 2:
FooInitProtocol = ProtocolOf["Foo.__init__"]

Should be equal to:

class FooInitProtocol(Protocol):
    def __call__(a: int, b: float) -> None: ...

Callable / Protocol to ParamSpec / Returning to use in typing

I see typing.get_args but it doesn't looks suitable for typing. Also

from collections.abc import Callable
from typing import get_args

FooSignature = Callable[[int, float], float]
get_args(FooSignature)  # == [[int, float], float]

Instead of that it should be way to define FooParamSpec / FooReturning

Bonus

there are no way to convert TypedDict to ParamSpec.kwargs
UPD: is't bound to typing.Unpack

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions