繁体   English   中英

当 function 只能返回 str 时,mypy 抱怨返回值类型不兼容(得到“可选 [str]”,预期为“str”)

[英]mypy complains Incompatible return value type (got “Optional[str]”, expected “str”) when a function can only return str

import os
from typing import Optional

_DEFAULT = 'abc'

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

对于这个 function,mypy 会抱怨

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

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

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

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM