【问题标题】:Why am I getting a mypy error for Optional type when I have early return for when value is None?当我提前返回值为 None 时,为什么我会收到 Optional 类型的 mypy 错误?
【发布时间】:2020-12-31 12:46:22
【问题描述】:

如果我在使用 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 为return sorted(d[f2] + [s]) 行提供了error: Unsupported left operand type for + ("None")note: Left operand is of type "Optional[List[str]]",即使我在值为None 时提前返回。

非常感谢任何帮助。

【问题讨论】:

    标签: python mypy python-typing


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 2021-12-16
      • 2020-11-05
      相关资源
      最近更新 更多