-
Is it possible to type def run_handler(handler) -> bool:
return run_handler_magic(handler)
async def async_handler(name: str, **kwargs: Any) -> bool:
return True
def sync_handler(name: str, **kwargs: Any) -> bool:
return True
def gen_handler(name: str, **kwargs: Any) -> bool:
yield True I was hoping to get something like this working....but I just can't get it accepted by mypy: class Handler(Protocol):
@overload
def __call__(self, name: str, **kwargs: Any) -> bool: ...
@overload
def __call__(self, name: str, **kwargs: Any) -> Generator[Any, None, bool]: ...
@overload
async def __call__(self, name: str, **kwargs: Any) -> bool: ... FWIW, I think I've got this working...but I really wanted to avoid littering several classes with all these overloads & dense typing and just use a @overload
def run_handler(handler: Callable[[str], bool]) -> None: ...
@overload
def run_handler(handler: Callable[[str], Awaitable[bool]]) -> None: ...
@overload
def run_handler(handler: Callable[[str], Generator[Any, None, bool]]) -> None: ...
def run_handler(handler) -> bool:
return run_handler_magic(handler) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You could use a SyncHandler: TypeAlias = Callable[[str], bool]
AsyncHandler: TypeAlias = Callable[[str], Awaitable[bool]]
GenHandler: TypeAlias = Callable[[str], Generator[Any, None, bool]]
def run_handler(handler: SyncHandler | AsyncHandler | GenHandler) -> bool:
return run_handler_magic(handler) |
Beta Was this translation helpful? Give feedback.
You could use a
Union
instead of usingoverload
, since the return type is always the same, andTypeAlias
to keep things readable: