Mypy and `None`



取以下函数:

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丢失,并返回错误。

我个人使用类型是为了可读性和避免bug。获得这样的错误(通常是延迟初始化和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

最新更新