当Callable返回类型为bool / numeric时,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应该捕获错误是我误会了吗?还是在布尔值和数字类型之间进行某种类型的静类型强制?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)