-
Hi, import asyncio
import inspect
from typing import Awaitable, Callable, Union
stored_callback: Callable[[int], None]
def set_callback(user_callback: Callable[[int], Union[None, Awaitable[None]]]) -> None:
if (inspect.iscoroutinefunction(user_callback)):
# user_callback type: Callable[[int], Awaitable[None]]
def wrapped_callback(param: int):
asyncio.create_task(user_callback(param))
stored_callback = wrapped_callback
else:
# user_callback type: Callable[[int], None]
stored_callback = user_callback Also, if there is some better user-friendly way how to handle both sync and async callbacks, please let me know. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
No, pyright doesn't currently know about We do occasionally add support for new type guards, but every case requires specialized logic and adds complexity (and in some cases degrades overall analysis performance), so we have a high bar for which cases to support. That means we need evidence that it's a frequently-used idiom in Python code and would benefit some reasonable number of pyright users. That evidence usually takes the form of:
I don't think We recently added a new mechanism called "user-defined type guards" that allows you to write your own type guard functions. That could be a good solution in this case. For details, refer to PEP 647. |
Beta Was this translation helpful? Give feedback.
No, pyright doesn't currently know about
inspect.iscoroutinefunction
for type narrowing. The full list of supported type guards can be found here: https://github.com/microsoft/pyright/blob/master/docs/type-concepts.md#type-guards.We do occasionally add support for new type guards, but every case requires specialized logic and adds complexity (and in some cases degrades overall analysis performance), so we have a high bar for which cases to support. That means we need evidence that it's a frequently-used idiom in Python code and would benefit some reasonable number of pyright users. That evidence usually takes the form of: