簡體   English   中英

當我提前返回值為 None 時,為什么我會收到 Optional 類型的 mypy 錯誤?

[英]Why am I getting a mypy error for Optional type when I have early return for when value is None?

對於 mypy 遇到的錯誤,我將不勝感激。

我的 function 看起來像:

def get_result(
    f1: float,
    l: List[float],
    d: Dict[float, Optional[List[str]]],
    f2: float,
    s: str
) -> Optional[List[str]]:
    if f1 is in l:
        if d[f2] is None:
            return [s]
        else:
            return sorted(d[f2] + [s])
    return d[f2]

然而,mypy 給出error: Unsupported left operand type for + ("None") ,注意:對於return sorted(d[f2] + [s])note: Left operand is of type "Optional[List[str]]"雖然當值為無時我有一個早期的回報。

任何幫助深表感謝。

我的理解是 Mypy 不夠聰明,無法記住字典的特定項目在is Noneisinstance檢查之后具有特定類型。 如果您直接為該項目命名,它可以記住這些事情。 在您的示例中:

def get_result(
    f1: float,
    l: List[float],
    d: Dict[float, Optional[List[str]]],
    f2: float,
    s: str
) -> Optional[List[str]]:
    # explicitly name the item that we care about
    d_f2 = d[f2]
    if f1 is in l:
        # use the given name directly
        if d_f2 is None:
            return [s]
        else:
            return sorted(d_f2 + [s])
    return d_f2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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