簡體   English   中英

如何使用mypy的類型檢查來強制調用類型的簽名

[英]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...

我遇到兩個問題:

  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 

我有沒有辦法編寫一個將另一個函數作為輸入的函數,並使用類型檢查來強制輸入函數具有正確的簽名?

不幸的是,似乎mypy目前無法推斷x的正確類型,因此我認為您可以做的最好的就是使用typing.castx強制為所需的類型:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM