AnyOf - Union for return types
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
Sometimes a function or method can return one of several types, depending on the passed in arguments or external factors. Best example is probably open(), but there are other examples in the standard library, like shutil.copy()[1]. In many of those cases, the caller knows what return type to expect.
Currently there are several options, but none of them is really satisfactory:
- Use
@overload. This is the best solution if it can be used. But that is often not the case, like in the examples above. - Use a mypy plugin. This solution does not scale to outside the standard library (and arguably not even inside it) and is mypy-specific.
- Use
Unionas the return type. This is usually not recommended, since it means that the caller needs to useisinstance()to use the return type. - Use
Anyas the return type. This is currently best practice in those cases, but of course provides no type safety at all.
Therefore, I propose to add another type, for example AnyOf[...] that acts like Union, but can be used everywhere any of its type arguments could be used.
from datetime import date
x: AnyOf[str, date] = ...
s: str = x # ok
dt: date = x # ok
i: int = x # type error
u: Union[str, bytes] = x # ok
x = u # type error (although the type checker could do something smart here and infer that u can only be str here)
I also think that the documentation should make it clear that using AnyOf is a code smell.
[1] Currently the type behaviour in shutil is broken in my opinion, but that does not change the fact that currently it is as it is.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
阅读 AnyOf 提案,并将其中的示例—open()、shutil.copy()、Union 和 @overload—与当前 typing 行为进行比较。查看 issue 讨论,确认是否已就语义和文档达成一致;完成意味着有一份已确定的规范,涵盖对每个成员类型的赋值、Union 兼容性以及无效类型。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- compilers
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 冷清
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100