Skip to content

Instantly share code, notes, and snippets.

@mypy-play
Created July 21, 2024 11:04
Show Gist options
  • Save mypy-play/f52c95a6ce272f6ea3f333a4bd8345bd to your computer and use it in GitHub Desktop.
Save mypy-play/f52c95a6ce272f6ea3f333a4bd8345bd to your computer and use it in GitHub Desktop.
Shared via mypy Playground
from collections.abc import Callable, Iterable, Iterator
from typing import TypeVar, TypeAlias
from contextlib import contextmanager
_T = TypeVar('_T')
GenericFn = Callable[[_T], _T]
@contextmanager
def make_generic() -> Iterator[GenericFn[_T]]:
def rv(obj: _T) -> _T:
return obj
yield rv
ExplicitAliasGenericFn: TypeAlias = Callable[[_T], _T]
@contextmanager
def make_generic_explicit() -> Iterator[ExplicitAliasGenericFn[_T]]:
def rv(obj: _T) -> _T:
return obj
yield rv
@contextmanager
def make_generic_inline() -> Iterator[Callable[[_T], _T]]:
def rv(obj: _T) -> _T:
return obj
yield rv
NotGenericFn = Callable[[Callable[[], None]], None]
@contextmanager
def make_not_generic() -> Iterator[NotGenericFn]:
def rv(fn: Callable[[], None]) -> None:
return fn()
yield rv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment