Introduce a Not type
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
This is a continuation of this discussion on the Intersection issue.
I have a different use case for the Not[...] type, but it is related to the original discussion. My usecase is to be able to tell the type checker that two types can never have an intersection. The specific case is for the phantom-types library where there are two types NonEmpty and Empty.
Currently there is no way to tell mypy that a variable can't both be NonEmpty and Empty, so this code passes without error:
from __future__ import annotations
from phantom.sized import NonEmpty, Empty
i: tuple[int, ...] = ()
assert isinstance(i, Empty)
assert isinstance(i, NonEmpty)
reveal_type(i)
The output shows that mypy interprets i as an intersection between tuple, Empty and NonEmpty:
intx.py:9: note: Revealed type is 'intx.<subclass of "tuple", "Empty", and "NonEmpty">'
Of course this code would error at runtime, but it would be preferable if this could be expressible so that type checkers can give an error here, similarly to how mypy gives errors for unreachable code.
A suggestion for how this could be expressed is to allow subclassing a Not type, so simplified the definitions of the two mentioned types would like this:
class NonEmpty:
...
class Empty(Not[NonEmpty]):
...
There are also other types in the library that would benefit from this like TZAware and TZNaive.
Edit: To clarify, I think that this type would be valuable even without an Intersection type which is why I opened a separate issue. This is because (as showed in the example) there already implicit intersections in mypy. I don't know how the other type checkers treats this.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
先阅读链接的 Intersection 讨论以及 phantom-types 中的 sized.py 和 datetime.py 示例。然后检查 issue 中展示的 mypy 行为,并比较其他类型检查器如何处理隐式交集。完成的标准是:有一个经维护者批准的用于表达不相交类型的设计,并且各检查器的行为已达成一致。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100