首页 > 解决方案 > 处理 Python 中缺少非空断言运算符

问题描述

我想允许 Mypy 的strict_optional标志。但是,考虑一下:

emails = [get_user(uuid).email for uuid in user_uuids]

where理论上get_user可以返回None,但在这个用例中,我知道它不能(如果确实有异常,我也可以)。这必须变成:

emails = []
for uuid in user_uuids:
    user = get_user(uuid)
    assert user is not None
    emails.append(user.email)

在 TypeScript 中,有一个非空断言运算符,它允许您只添加一个!(如getUser(uuid)!.email)。

有没有更好或更优雅的方法来处理这个问题?

标签: pythonmypy

解决方案


没有理由不能在条件中使用相同的调用,所以

emails = [get_user(uuid).email for uuid in user_uuids if get_user(uuid)]

将工作


推荐阅读