首页 > 解决方案 > 当我提前返回值为 None 时,为什么我会收到 Optional 类型的 mypy 错误?

问题描述

对于 mypy 遇到的错误,我将不胜感激。

我的函数看起来像:

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")and note: Left operand is of type "Optional[List[str]]"for 这return sorted(d[f2] + [s])条线,即使当值为 None 时我有一个早期的回报。

任何帮助深表感谢。

标签: pythonmypypython-typing

解决方案


我的理解是,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

推荐阅读