哪个 python 静态检查器可以捕获“忘记等待"的问题? [英] Which python static checker can catch 'forgotten await' problems?

查看:72
本文介绍了哪个 python 静态检查器可以捕获“忘记等待"的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

from typing import AsyncIterable

import asyncio


async def agen() -> AsyncIterable[str]:
    print('agen start')
    yield '1'
    yield '2'


async def agenmaker() -> AsyncIterable[str]:
    print('agenmaker start')
    return agen()


async def amain():
    print('amain')
    async for item in agen():
        pass
    async for item in await agenmaker():
        pass
    # Error:
    async for item in agenmaker():
        pass


def main():
    asyncio.get_event_loop().run_until_complete(amain())


if __name__ == '__main__':
    main()

如您所见,它带有类型注释,并且包含一个容易遗漏的错误.

As you can see, it is type-annotated, and contains an easy-to-miss error.

然而,pylintmypy 都没有发现这个错误.

However, neither pylint nor mypy find that error.

除了单元测试,还有哪些方法可以捕获此类错误?

Aside from unit tests, what options are there for catching such errors?

推荐答案

MyPy 完全有能力发现这个问题.问题是未检查未注释的函数.将违规函数注释为 ->;无,并被正确检查和拒绝.

MyPy is perfectly capable of finding this issue. The problem is that unannotated functions are not inspected. Annotate the offending function as -> None and it is correctly inspected and rejected.

# annotated with return type
async def amain() -> None:
    print('amain')
    async for item in agen():
        pass
    async for item in await agenmaker():
        pass
    # Error:
    async for item in agenmaker(): # error: "Coroutine[Any, Any, AsyncIterable[str]]" has no attribute "__aiter__" (not async iterable)

        pass

如果您想消除此类问题,请使用标志 --disallow-untyped-defs--check-untyped-defs.

If you want to eliminate such issues slipping through, use the flags --disallow-untyped-defs or --check-untyped-defs.

没有类型注解的函数会被mypy认为是动态类型的:

MyPy: Function signatures and dynamic vs static typing

A function without type annotations is considered to be dynamically typed by mypy:

def greeting(name):
    return 'Hello ' + name

默认情况下,mypy 不会对动态类型函数进行类型检查.这意味着除了少数例外,mypy 不会报告任何常规未注释 Python 的错误.

By default, mypy will not type check dynamically typed functions. This means that with a few exceptions, mypy will not report any errors with regular unannotated Python.

这篇关于哪个 python 静态检查器可以捕获“忘记等待"的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆