![](/img/trans.png)
[英]mypy complains: function type annotation with Type[TypeVar['T', str, date]] and T output: Incompatible return value type (got "str", expected "date")
[英]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 B
或A 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.