Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created May 3, 2025 16:16
Show Gist options
  • Save mypy-play/4ecc8023ee8a063e7dd8053ba073ceaa to your computer and use it in GitHub Desktop.
Save mypy-play/4ecc8023ee8a063e7dd8053ba073ceaa to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from collections.abc import Callable
import typing_extensions as t
P = t.ParamSpec("P")
T_co = t.TypeVar("T_co", covariant=True)
class ExpectCallable(t.Generic[P, T_co]): ...
class ExpectType(ExpectCallable[P, T_co]): ...
def expect(
v: Callable[P, T_co], /, *args: P.args, **kwargs: P.kwargs
) -> ExpectCallable[P, T_co]:
return ExpectType() if isinstance(v, type) else ExpectCallable()
class A:
def __init__(self, inp: str, /) -> None: ...
def fn(inp: str, /) -> None: ...
t.assert_type(expect(A), ExpectType[[], A]) # Shouldn't be allowed
t.assert_type(expect(A), ExpectCallable[[], A])
t.assert_type(expect(A, ""), ExpectCallable[[str], A])
t.assert_type(expect(fn, "inp"), ExpectCallable[[str], None])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment