承担以下职能:
from typing import Optional
def area_of_square(width: Optional[float] = None,
height: Optional[float] = None) -> float:
if width is None and height is None:
raise ValueError('You have not specified a width or height')
if width is not None and height is not None:
raise ValueError('Please specify a width or height, not both')
area = width**2 if width is not None else height**2
return area在area =行,mypy抱怨height不可能。
我可以在它的上方加上以下一行:
height = typing.cast(int, height)但这是不正确的,因为height可能是None。在任何类型的逻辑中转换的包装都会使类型丢失,我又回到了错误的位置。
我个人使用打字的可读性和避免错误。像这样的错误(通常是延迟初始化和None的其他类似用途)会使这个目的落空,所以我喜欢在有意义的时候修复它们。
在这种情况下,人们使用哪些策略?
发布于 2022-06-30 09:38:57
mypy不能用一个公共条件绑定多个变量。
下面的行类型保护这两个变量:
a is None and b is None
a is not None and b is not None因此,它们可以按预期工作,而另一个条件是:
a is not None or b is not None不能为mypy提供信息,您不能表示“至少其中一个是not None”,并将其用于类型检查。
我宁愿做这:
from typing import Optional
def area_of_square(width: Optional[float] = None,
height: Optional[float] = None) -> float:
if width is not None and height is not None:
raise ValueError('Please specify a width or height, not both')
elif width is not None:
area = width**2
elif height is not None:
area = height**2
else:
raise ValueError('You have not specified a width or height')
return areahttps://stackoverflow.com/questions/72809115
复制相似问题