【问题标题】:mypy complains Incompatible return value type (got "Optional[str]", expected "str") when a function can only return str当函数只能返回 str 时,mypy 抱怨返回值类型不兼容(得到“Optional [str]”,预期为“str”)
【发布时间】:2021-05-08 07:21:44
【问题描述】:
import os
from typing import Optional

_DEFAULT = 'abc'

def _get_value(param: Optional[str]) -> str:
    return param or os.getenv("PARAM", _DEFAULT)

对于这个函数,mypy 会抱怨

Incompatible return value type (got "Optional[str]", expected "str")

但我认为这个函数永远不会返回None。我错过了什么吗?

【问题讨论】:

    标签: python mypy


    【解决方案1】:

    mypy 类型检查器似乎无法解析 or 条件。您必须明确检查 None 值:

    if param:
        return param
    else:
        return os.getenv("PARAM", _DEFAULT)
    

    编辑:上面的代码在技术上检查 falsy 值而不是 None,但它在功能上等同于您的示例。

    【讨论】:

      【解决方案2】:

      mypy 似乎缺少一些“旧式三元”函数的推断——A or BA and B or C 形式的那些函数

      查看reveal_type 的三个表达式

      # reveal_type(param)
      t.py:9: note: Revealed type is 'Union[builtins.str, None]'
      # reveal_type(os.getenv("PARAM", _DEFAULT)
      t.py:10: note: Revealed type is 'builtins.str'
      # param or reveal_type(os.getenv("PARAM", _DEFAULT)
      t.py:11: note: Revealed type is 'Union[builtins.str, None]'
      

      你可以通过使用真正的三元来解决这个问题:

      def _get_value(param: Optional[str]) -> str:
          return param if param is not None else os.getenv("PARAM", _DEFAULT)
      

      【讨论】:

        猜你喜欢
        • 2022-12-17
        • 1970-01-01
        • 2017-01-19
        • 1970-01-01
        • 2022-01-14
        • 1970-01-01
        • 2022-01-08
        • 2021-11-07
        • 2021-12-31
        相关资源
        最近更新 更多