Python 打字和期货
Python typings and futures
我很高兴使用 typing module in Python 3. Also, I'm very glad to use asyncio 而不是 twisted
、tornado
和替代品。
我的问题是如何正确定义协程的结果?
我们应该说它只是一个协程吗?示例 1:
async def request() -> asyncio.Future:
pass
或者我们应该将协程的结果类型定义为 returning 值的类型?示例 2:
async def request() -> int:
pass
如果是,那么如何使用普通函数,return 期货?示例 3:
def request() -> asyncio.Future:
f = asyncio.Future()
# Do something with the future
return f
这样做对吗?那么我们如何判断未来的预期结果呢?
正如@jonrsharpe 所说,typing.Awaitable 非常适合这项任务。
一般来说,您应该使用正则 return 值(例如 int
、float
、bool
、None
等),但是如果您将它用作可调用它应该如下所示:
async def bar(x: int) -> str:
return str(x)
cbar: Callable[[int], Awaitable[str]] = bar
更多信息:here.
您也可以查看此 issue 以获得 mypy
支持。
我很高兴使用 typing module in Python 3. Also, I'm very glad to use asyncio 而不是 twisted
、tornado
和替代品。
我的问题是如何正确定义协程的结果?
我们应该说它只是一个协程吗?示例 1:
async def request() -> asyncio.Future:
pass
或者我们应该将协程的结果类型定义为 returning 值的类型?示例 2:
async def request() -> int:
pass
如果是,那么如何使用普通函数,return 期货?示例 3:
def request() -> asyncio.Future:
f = asyncio.Future()
# Do something with the future
return f
这样做对吗?那么我们如何判断未来的预期结果呢?
正如@jonrsharpe 所说,typing.Awaitable 非常适合这项任务。
一般来说,您应该使用正则 return 值(例如 int
、float
、bool
、None
等),但是如果您将它用作可调用它应该如下所示:
async def bar(x: int) -> str:
return str(x)
cbar: Callable[[int], Awaitable[str]] = bar
更多信息:here.
您也可以查看此 issue 以获得 mypy
支持。