GvRs ndb库以及单片 --据我理解--现代Javascript使用生成器来使异步代码看起来像阻塞代码。
东西都是用@ndb.tasklet装饰的。当他们想将执行返回给runloop时,当他们准备好结果时,他们会yield (或者别名raise StopIteration(value) ):
@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()一切都很好。但是如何添加类型注释呢?正确的类型是:
到目前为止,我只提出了异步函数的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。
发布于 2019-01-21 05:29:44
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 Nonehttps://stackoverflow.com/questions/54010046
复制相似问题