str: -6ren">
gpt4 book ai didi

python - mypy 提示 Incompatible return value type (got "Optional[str]"expected "str") when a function can only return str

转载 作者:行者123 更新时间:2023-12-05 02:02:09 26 4
gpt4 key购买 nike

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。我错过了什么吗?

最佳答案

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

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

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

关于python - mypy 提示 Incompatible return value type (got "Optional[str]"expected "str") when a function can only return str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66038058/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com