python - 处理 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
)。
有没有更好或更优雅的方法来处理这个问题?
解决方案
没有理由不能在条件中使用相同的调用,所以
emails = [get_user(uuid).email for uuid in user_uuids if get_user(uuid)]
将工作
推荐阅读
- javascript - 数组项到Javascript中数组中对象的属性
- junit4 - 如何在不使用 AssertNotNull 的情况下编写 Junit 测试用例
- python - 在 Perl 中使用 Spacy 和 Inline::Python 对数 MB 的原始文本进行 Lemmatize。为什么这么慢?
- javascript - Chart.js 折线图不会从零开始或第一个刻度作为最小值
- pandas - 获取熊猫数据框中特定列的累积总和和平均值
- performance - 带有频繁单词的法国地址的慢速弹性搜索查询
- c++ - 调用无害函数时在优化版本的程序中发生崩溃
- python - 如何减少重叠霍夫线?
- javascript - Java中如何追踪前任King是正常跳还是被Capturing跳
- python - cMake find_package Python