首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mypy和‘`None`’

Mypy和‘`None`’
EN

Stack Overflow用户
提问于 2022-06-30 00:18:34
回答 1查看 228关注 0票数 0

承担以下职能:

代码语言:javascript
复制
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不可能。

我可以在它的上方加上以下一行:

代码语言:javascript
复制
    height = typing.cast(int, height)

但这是不正确的,因为height可能是None。在任何类型的逻辑中转换的包装都会使类型丢失,我又回到了错误的位置。

我个人使用打字的可读性和避免错误。像这样的错误(通常是延迟初始化和None的其他类似用途)会使这个目的落空,所以我喜欢在有意义的时候修复它们。

在这种情况下,人们使用哪些策略?

EN

回答 1

Stack Overflow用户

发布于 2022-06-30 09:38:57

mypy不能用一个公共条件绑定多个变量。

下面的行类型保护这两个变量:

代码语言:javascript
复制
a is None and b is None
a is not None and b is not None

因此,它们可以按预期工作,而另一个条件是:

代码语言:javascript
复制
a is not None or b is not None

不能为mypy提供信息,您不能表示“至少其中一个是not None”,并将其用于类型检查。

我宁愿做

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72809115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档