Interest check: implement __bool__ for Result and Maybe
还没有人认领这个 Issue。
评估
调研方向
该 issue 没有指定具体的文件或测试。首先定位 Result 和 Maybe 的实现及其现有的类型收窄测试,然后检查如何区分 Success 和 Failure。Done 应包括已约定的两种类型的 bool 行为、对已揭示类型的覆盖,以及考虑与现有 truthiness 假设的兼容性。
由索引模型根据 Issue 内容生成。
描述
Long before I found Returns, I implemented my own Result monad from scratch. It was a lot of fun, and right now it coexists with Returns as the library it's a part of is being incrementally deprecated. At some point, I decided it would be nice if I could do things like this:
result = some_function() # Result[S, F]
if result:
reveal_type(result) # Success[S]
else:
reveal_type(result) # Failure[F]
It's worked great. I have my own analogue to is_successful, but with __bool__ I don't even have to import it. Also, it actually works better than my functions: my analogue is a pair of TypeGuard functions (TypeIs didn't exist yet), so even after narrowing the container type in the first if, the else would have no type information about the container. Cf., __bool__(self) -> Literal[False] and __bool__(self) -> Literal[True] make type narrowing work perfectly, and it feels very pythonic, imo.
As I update more and more code to use Returns, instead, I find this to be the one thing about my library that I actually miss. There are a lot of cases where I could reach for match for something as ergonomic, but most of the time I'm only interested in Success vs. Failure; match is overkill if I don't need to peak at the contained value.
The one drawback I anticipate to adding this feature would be the possibility of breaking any code that's relying on the default object.__bool__ behavior to differentiate a Failure from eg. a None... but hopefully, anybody using this library would have their Optionals wrapped in a Maybe already?
- 主要语言
- Python
- 星标
- 4.4k
- 派生
- 154
- 平均合并
- 3 小时 5 分钟
- 30 天内合并 PR
- 22
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
dry-python/returns 的其他 Issue
-
难度 4/5 3-5 天 新手友好度 52/100
dry-python/returns#2365 ·
-
难度 5/5 一周以上 新手友好度 25/100
dry-python/returns#2355 · 1 条评论 ·
-
bug
难度 4/5 3-5 天 新手友好度 45/100
dry-python/returns#2295 · 4 条评论 · 1 个 reaction ·
-
bug
难度 4/5 3-5 天 新手友好度 45/100
dry-python/returns#2253 · 2 条评论 ·
-
Incorrect result type for `returns.curry.partial` with keyword arguments for positional parameters 未关闭bug
难度 3/5 1-2 天 新手友好度 45/100
dry-python/returns#2191 · 1 条评论 ·
查看 dry-python/returns 的全部 Issue
相似的 Issue
-
bug confirmed issue
难度 2/5 1-3 小时 新手友好度 75/100
open-webui/open-webui#30750 · 1 条评论 ·
-
难度 2/5 1-3 小时 新手友好度 75/100
-
enhancement
难度 2/5 1-3 小时 新手友好度 75/100
OpenwaterHealth/openmotion-bloodflow-app#604 · 1 条评论 ·
-
难度 2/5 1-3 小时 新手友好度 70/100
-
good first issue
难度 1/5 1 小时以内 新手友好度 90/100