python / python/typing

Suggestion: Allow free type variables in type variable bounds that permeate beyond

未关闭
#1,311 1 条评论 7 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Suppose we have the following code:

T_co = TypeVar("T_co", covariant=True)

class CanProduce(Protocol[T_co]):
    def produce(self) -> T_co:
        ...

T_in = TypeVar("T_in")
U = TypeVar("U")

@dataclass
class Container(Generic[T_in]):
    value: T_in

    def produce_from_value(self: Container[CanProduce[U]]) -> U:
        return self.value.produce()

This code has an undesirable property: Since T_in is invariant, produce_from_value can only be called on instances of Container whose type parameter is exactly CanProduce[U], for some U:

class IntProducer(CanProduce[int]):
    def produce(self) -> int:
        return 42

c: Container[IntProducer] = Container(IntProducer())
c.produce_from_value()  # this produces a type error

It would be ideal if we could communicate that in this method (which need not be an instance method, it could be a discrete function also), the type parameter behaves as though it were covariant, where any subtype of CanProduce[U] is valid.

In fact, there exists a mechanism for doing this in other situations. Consider if we have the following non-generic protocol:

class SupportsIndex(Protocol):
    def __index__(self) -> int:
        ...

We can then make a method index_from_value that works with all subtypes of SupportsIndex:

SI = TypeVar("SI", bound=SupportsIndex)

@dataclass
class Container(Generic[T_in]):
    value: T_in
    
    def index_from_value(self: Container[SI]):
        return self.value.__index__

Now, the following is valid:

c: Container[int] = Container(27)
c.index_from_value()

Unfortunately, this method cannot be used with generic protocols, because the following is invalid:

U = TypeVar("U")
CPU = TypeVar("CPU", bound=CanProduce[U])  # this produces a type error

I suggest altering the restriction to allow this trick to work.

贡献指南

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

从这里开始

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

调研方向

先从 issue 中的泛型 protocol、Container 和 TypeVar 示例开始,然后将它们与非泛型的 SupportsIndex 情况进行比较。只有在所提议的限制变更及其对 subtype 的行为都被明确规定到足以进行评估时,该 issue 才准备好着手处理。

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

评估

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

把新 issue 发到你的邮箱

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