python / python/mypy

Decorator with constrained TypeVar specializes to first constraint

未关闭
#20,437 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

bug topic-calls
主要语言
Python
星标
20.6k
派生
3.3k
PR 合并指标
PR 指标待抓取

描述

Bug Report

Changing the order of constraints of TypeVar T changes whether or not mypy passes. The wrapped method always gets narrowed to whatever the first constraint type is set to.

To Reproduce

from collections.abc import Callable
from typing import TypeVar, reveal_type


T = TypeVar("T", str, bytes)  # fails
# T = TypeVar("T", bytes, str)  # passes

def decorator(fn: Callable[[T], T]) -> Callable[[T], T]:
    def wrapped(data: T) -> T:
        return fn(data)
    return wrapped

@decorator
def process(data: T) -> T:
    return data

b: bytes = b"test"
result = process(b)

Or see mypy playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=12fd2e05764d26a16cd1d16a10897671

Expected Behavior

Ideally pass for both versions, or consistently fail regardless of the constraint order.
On pyright playground the revealed types match my expectations and pass with either TypeVar order

Actual Behavior

mypy passes or fails depending on TypeVar constraint order, or the data input type

Your Environment

Same behavior with all tested mypy versions (1.6.0 .. 1.19.1) and python 3.11+

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先运行 issue 中的最小 decorator 和受约束 TypeVar 复现用例,然后跟踪 mypy 对约束特化和包装后的 callable 的处理。完成的标准是结果不再依赖 TypeVar 约束的顺序,并且覆盖两种约束顺序。

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

评估

技术栈
python
领域
devtools
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
42/100

把新 issue 发到你的邮箱

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