[英]How can I use mypy's typechecking to enforce the signature of a callable type
我有一個將另一個函數x作為參數的函數。 函數x可以具有2種不同類型的簽名,我想通過類型提示來強制執行此操作:
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
我有沒有辦法編寫一個將另一個函數作為輸入的函數,並使用類型檢查來強制輸入函數具有正確的簽名?
不幸的是,似乎mypy目前無法推斷x
的正確類型,因此我認為您可以做的最好的就是使用typing.cast
將x
強制為所需的類型:
from typing import *
from inspect import signature
TYPE_A = Callable[[int, int], int]
TYPE_B = Callable[[int], int]
def my_func(x: Union[TYPE_A, TYPE_B]):
sig = signature(x)
if len(sig.parameters.values()) == 1:
x = cast(TYPE_B, x)
x(1)
else:
x = cast(TYPE_A, x)
x(1, 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.