取以下函数:
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 =
行,mymyy抱怨height
可能是None。
我可以在上面加上下面一行:
height = typing.cast(int, height)
但这是不正确的,因为height
可能是None
。在任何类型的逻辑中包装该强制转换都会使mymyy丢失,并返回错误。
None
的其他类似使用)有点违背了目的,所以我喜欢在有意义的时候修复它们。
在这种情况下人们会使用哪些策略?
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 area