当Callable返回类型为bool / numeric时,mypy无法检测到错误

时间:2020-09-13 18:57:58

标签: python mypy

以下文件test.py由于Callable的返回类型不匹配而具有多种类型错误。

from typing import Callable


def func() -> bool:
    return True


f1: Callable[[], bool] = func   # okay
f2: Callable[[], float] = func  # should be error: f2's return type does not match func's

r1: float = f1()                # should be error: r1's type float does not match f1's return type bool
r2: float = func()              # should be error: r2's type float does not match func's return type bool
r3: float = f2()                # okay, given how f2 is declared

但mypy没有报告错误:

$ mypy test.py --check-untyped-defs
Success: no issues found in 1 source file

很奇怪,如果func的返回类型是str而不是bool,则检测到错误

from typing import Callable


def func() -> str:
    return 'abc'


f1: Callable[[], str] = func    # okay
f2: Callable[[], float] = func  # mypy error, line 9

r1: float = f1()                # mypy error, line 11
r2: float = func()              # mypy error, line 12
r3: float = f2()                # okay, given how f2 is declared
$ mypy test.py --check-untyped-defs
test.py:9: error: Incompatible types in assignment (expression has type "Callable[[], str]", variable has type "Callable[[], float]")
test.py:11: error: Incompatible types in assignment (expression has type "str", variable has type "float")
test.py:12: error: Incompatible types in assignment (expression has type "str", variable has type "float")
Found 3 errors in 1 file (checked 1 source file)

这是Python 3.7.5。无论返回类型如何,我都认为mypy应该捕获错误是我误会了吗?还是在布尔值和数字类型之间进行某种类型的静默类型强制?

0 个答案:

没有答案