GvRs App Engine ndb Library以及monocle并且——据我所知——现代 Javascript 使用生成器使异步代码看起来像阻塞代码。
事物用@ndb.tasklet
装饰。他们yield
当他们想要将执行交还给 runloop 并且当他们准备好结果时他们 raise StopIteration(value)
(或别名 ndb.Return
):
@ndb.tasklet
def get_google_async():
context = ndb.get_context()
result = yield context.urlfetch("http://www.google.com/")
if result.status_code == 200:
raise ndb.Return(result.content)
raise RuntimeError
要使用这样的函数,您需要返回一个 ndb.Future
对象并调用 get get_result()
函数以等待结果并获取它。例如:
def get_google():
future = get_google_async()
# do something else in real code here
return future.get_result()
这一切都非常好。但如何添加类型注释?正确的类型是:
- get_google_async() -> ndb.Future(通过 yield)
- ndb.tasklet(get_google_async) -> ndb.Future
- ndb.tasklet(get_google_async).get_result() -> str
到目前为止,我只想到了 cast
异步函数。
def get_google():
# type: () -> str
future = get_google_async()
# do something else in real code here
return cast('str', future.get_result())
不幸的是,这不仅与 urlfetch
有关,而且与数百种方法有关 - 主要是 ndb.Model。
最佳答案
get_google_async
本身是一个生成器函数,所以我认为类型提示可以是 () -> Generator[ndb.Future, None, None]
。
至于 get_google
,如果您不想转换,类型检查可能会起作用。
喜欢
def get_google():
# type: () -> Optional[str]
future = get_google_async()
# do something else in real code here
res = future.get_result()
if isinstance(res, str):
return res
# somehow convert res to str, or
return None
关于python - 为 ndb.tasklets 类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54010046/