python / python/typing

TypeVar substitution in get_type_hints

未关闭
#776 10 条评论 9 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: feature
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

When it comes to generic classes, type annotations retrieved with get_type_hints are not really easy to use, as in the following example:

from typing import Generic, TypeVar, get_type_hints

T = TypeVar("T")
class A(Generic[T]):
    a: T

U = TypeVar("U")
class B(A[U]):
    b: U

assert get_type_hints(B) == {"a": T, "b": U}

It could be useful to add a TypeVar substitution to get_type_hints, for example with an additional substitute_type_vars parameter (with a False default)
By the way, get_type_hints could also allow to pass generic alias in order to substitute directly TypeVars with their related argument.

It would give for the example above:

assert get_type_hints(B, substitute_type_vars=True) == {"a": U, "b": U}  # typevars are consistent
assert get_type_hints(B[T], substitute_type_vars=True) == {"a": T, "b": T}
assert get_type_hints(B[int], substitute_type_vars=True) == {"a": int, "b": int}  # ready to use

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 get_type_hints API 和 issue 中的 generic-class 示例开始,然后检查当前如何表示 generic aliases 和 TypeVar 关系。完成标准是定义并实现提议的替换行为,包括默认禁用的参数和 alias 输入,并添加涵盖 B、B[T] 和 B[int] 的测试。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
devtools
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。