如何使用mypy的类型检查来强制执行可调用类型的签名

时间:2018-03-03 19:31:25

标签: python-3.x type-hinting mypy

我有一个函数,它将另一个函数x作为其​​参数。函数x可以有两种不同类型的签名,我想通过类型提示来强制执行:

TYPE_A = Callable[[int, int], int]
TYPE_B = Callable[[int], int]

def my_func(x: Union[TYPE_A, TYPE_B]) -> None:
    ...determine x is of which type and use x accordingly...

我遇到了两个问题:

  1. 我不知道如何检查x是TYPE_A还是TYPE_B。我尝试使用isinstance(x, TYPE_A)并生成类型错误。

  2. 如果我使用其他方式确定x的类型,例如,使用signature确定my_func内的x的签名(如果x有1个参数或2个参数) ,mypy仍然认为每当我运行x:

    时都会出现类型错误
    from inspect import signature
    def my_func(x: Union[TYPE_A, TYPE_B]):
        sig = signature(x)
        if len(sig.parameters.values()) == 1:
             x(1)  // mypy thinks this is a type error: too few args
        else:
             x(1, 2) // mypy thinks this is type error: too many args
    
  3. 有没有办法让我编写一个以另一个函数作为输入的函数,并使用类型检查来强制输入函数具有正确的签名?

1 个答案:

答案 0 :(得分:0)

不幸的是,似乎mypy目前无法推断出ScheduledExcecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(()->builder.getReloadingController().checkForReloading(null), delay, interval, TimeUnit.SECONDS); 的正确类型,所以我认为你能做的最好就是使用x强制{{1}到期望的类型:

typing.cast