python - 为 ndb.tasklets 类型注释

标签 python google-app-engine mypy

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/

相关文章:

node.js - 具有 OR 条件的 Google Datastore 过滤器

java - 如何删除 .jsp 中的 blob

java - App-Engine (Java) 文件上传

python - 通过 Windows 命令行运行 Python 脚本

python - 用于移植到 Python 代码的 Tcl 面向对象扩展

python - 使用 python 脚本更改 shell 中的工作目录

python - 引号中的 mypy 显式类型提示仍然给出未定义的错误

python - Windows - 无法通过 pip 安装 pyautogui - 错误 : Command "python setup.py egg_info" failed with error code 1

python - Mypy 在 PyQT 中的每个 connect() 上显示 "Callable... has no attribute "connect"

python - *(解包)运算符可以在 Python 中输入吗?或者任何其他可变参数函数使得所有可变类型都在结果类型中?