【问题标题】:type safety (mypy) for function parameters when using *args使用 *args 时函数参数的类型安全 (mypy)
【发布时间】:2018-06-17 09:01:34
【问题描述】:

使用mypy 对以下代码进行类型检查:

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

foo('ok', 2.2, 'bad')

也显示了无效调用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 能够报告问题的方式细化类型注释?

【问题讨论】:

  • @Kasramvd OP 希望 mypy 将 say_hi_and_call(foo, 'ok', 2.2, 'bad') 报告为错误。

标签: python types python-3.6 typechecking mypy


【解决方案1】:

好的,我想出的唯一解决方案是明确函数的数量,即

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_and_call_unarysay_hi_and_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]"

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2016-08-26
    • 2022-01-22
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多