我有一个函数,它将另一个函数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...
我遇到了两个问题:
我不知道如何检查x是TYPE_A
还是TYPE_B
。我尝试使用isinstance(x, TYPE_A)
并生成类型错误。
如果我使用其他方式确定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
有没有办法让我编写一个以另一个函数作为输入的函数,并使用类型检查来强制输入函数具有正确的签名?
答案 0 :(得分:0)
不幸的是,似乎mypy目前无法推断出ScheduledExcecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(()->builder.getReloadingController().checkForReloading(null),
delay, interval, TimeUnit.SECONDS);
的正确类型,所以我认为你能做的最好就是使用x
强制{{1}到期望的类型:
typing.cast