如何解决mypy中可选类型确定非None后的类型检查错误?
解决mypy对Optional[float]的类型检查报错问题
你遇到的是mypy的类型窄化(type narrowing)问题——虽然你已经通过if result is None排除了None的情况,但mypy有时无法正确推断后续代码中result的类型。以下几种方法可以解决:
方法1:使用类型断言(cast)
通过typing.cast明确告诉mypy此时result是float类型,前提是你已经确保result不可能为None:
from typing import Optional, cast, Any def method(args) -> Optional[float]: if some_case: return numerical_value # 修正原代码语法错误,去掉多余的`: float` return None def next_step(val: float) -> Any: return do_more_stuff result = method(stuff) if result is None: exit_early() next_step(cast(float, result))
方法2:重新赋值给新变量
在排除None后,把result赋值给一个新变量,mypy会自动推断这个新变量的类型为float:
from typing import Optional, Any def method(args) -> Optional[float]: if some_case: return numerical_value return None def next_step(val: float) -> Any: return do_more_stuff result = method(stuff) if result is None: exit_early() # 新变量会被mypy自动推断为float类型 valid_result = result next_step(valid_result)
方法3:使用海象运算符(Python 3.8+)
在判断None的同时完成赋值,直接得到非可选的变量:
from typing import Optional, Any def method(args) -> Optional[float]: if some_case: return numerical_value return None def next_step(val: float) -> Any: return do_more_stuff if (result := method(stuff)) is None: exit_early() # 此时result已被推断为float类型 next_step(result)
注意:原代码中return numerical_value: float是语法错误,需去掉: float,函数返回类型已通过-> Optional[float]标注,返回值无需额外类型标注。
内容的提问来源于stack exchange,提问作者kuanb
相关产品推荐
相关产品推荐

