Specify methods that are allowed for inference of partially initialized generics
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
The inference of generic types for classes in most type-checkers assume that all the generic types can be inferred from the parameters to __init__. This is not always the case. For example, it is a common pattern to create an empty container class and add elements to it later, e.g.:
a = []
a.append("hello world")
Currently for builtin classes, such as list or dict, this idiom is understood by MyPy, but not by Pyright. Moreover, even MyPy is incapable of applying this type inference to custom types (see https://github.com/python/mypy/issues/13134). As mentioned in that issue, the problem is not only with empty containers, but also with some widely used APIs, such as the Estimator API from scikit-learn and related projects, in which the type of the data used is only known when the fit method is called.
My proposal would be to add functionality to the type system to define which methods can be used to infer generic types, apart from __init__. This could be made for example with a decorator (e.g. allow_generic_inference), so that one can define a method such as:
@allow_generic_inference
def append(value: T):
...
In this case the value of the class generic parameter T could be inferred from append if it was undefined before.
I think this proposal may also be similar to the previously suggested TypeAssert mentioned by @erictraut in https://github.com/python/typing/discussions/1013#discussioncomment-1966238. However I am not completely sure that TypeAssert could do what I explained here. I am also not sure that the proposed TypeAssert syntax is better than a decorator.
I hope you too consider this proposal useful, and I look forward to your feedback.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
未指定源文件或测试。首先查看提案中关于空容器和 scikit-learn Estimator API 的示例,然后阅读链接的 MyPy issue 和 TypeAssert 讨论。完成的标准是就除 init 之外的方法是否可以推断泛型参数达成一致,并定义所接受的语法和行为。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- compilers
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100