mypy和``没有
采用以下功能:
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
在afir =
线上,mypy抱怨高度
可能无。
我可以在其上方添加以下行:
height = typing.cast(int, height)
但这是不正确的,因为高度
可以是none
。用任何形式的逻辑包裹该铸件会使Mypy迷失了,我又回到了错误。
我个人使用打字以进行可读性并避免错误。得到这样的错误(通常使用懒惰的初始化和none
的其他类似用途)会破坏目的,因此我喜欢在有意义的情况下修复它们。
在这种情况下,人们使用哪些策略?
Take the following function:
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
At the area =
line, mypy complains that height
could be None.
I could add the following line just above it:
height = typing.cast(int, height)
But that is not correct, since height
could be None
. Wrapping that cast in any sort of logic makes mypy get lost and I'm back to the error.
I personally use typing for readability and to avoid bugs. Getting errors like this (and often with lazy initialization and other similar uses of None
) kind of defeats the purpose, so I like to fix them when it makes sense.
What are some strategies people use in this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
mypy
无法用一个常见条件绑定多个变量。以下行类型guard两个变量:
因此它们按预期工作,而另一个条件:
mypy
不提供信息,您不能表达“至少其中一个是不是无
“并在类型检查中使用它。我会做
mypy
cannot bind multiple variables with one common condition.The following lines type guard both variables:
So they work as expected, while another condition:
is not informative for
mypy
, you cannot express "at least one of them isnot None
" and use it in type checking.I'd do this instead: