Python 使用*args时,为函数参数键入安全性(mypy)

Python 使用*args时,为函数参数键入安全性(mypy),python,types,python-3.6,typechecking,mypy,Python,Types,Python 3.6,Typechecking,Mypy,键入以下代码,并使用: 显示无效的调用也foo: error: Argument 3 to "foo" has incompatible type "str"; expected "int" 现在假设我们有一个如下所示的包装函数: from typing import Callable, Any def say_hi_and_call(func: Callable[..., Any], *args): print('Hi.') func(*args) 并使用它执行无效的调用

键入以下代码,并使用:

显示无效的调用也
foo

error: Argument 3 to "foo" has incompatible type "str"; expected "int"
现在假设我们有一个如下所示的包装函数:

from typing import Callable, Any

def say_hi_and_call(func: Callable[..., Any], *args):
    print('Hi.')
    func(*args)
并使用它执行无效的调用

say_hi_and_call(foo, 'ok', 2.2, 'bad')
mypy
不会报告任何错误,我们只会在运行时了解此错误:

TypeError: must be str, not int

我想早点发现这个错误。是否有可能以
mypy
能够报告问题的方式细化类型注释?

好的,我提出的唯一解决方案是使函数的算术显式化,即

from typing import Any, Callable, TypeVar

A = TypeVar('A')
B = TypeVar('B')
C = TypeVar('C')

def say_hi_and_call_ternary(func: Callable[[A, B, C], Any], a: A, b: B, c: C):
    print('Hi.')
    func(a, b, c)

def foo(a: str, b: float, c: int):
    print(a, b, c + 1)

say_hi_and_call_ternary(foo, 'ok', 2.2, 'bad')
当然,人们也需要一个类似的
say_hi_和call_monary
say_hi_和call_binary
等等

但是,由于我认为我的应用程序不会在PROD中爆炸,而不是保存一些LOC,因此当
mypy
能够报告错误时,我很高兴,现在情况肯定是这样的:

error: Argument 1 to "say_hi_and_call_ternary" has incompatible type "Callable[[str, float, int], Any]"; expected "Callable[[str, float, str], Any]"

@Kasramvd OP希望mypy报告
say_hi_和_call(foo'ok',2.2'bad')
为错误。
error: Argument 1 to "say_hi_and_call_ternary" has incompatible type "Callable[[str, float, int], Any]"; expected "Callable[[str, float, str], Any]"