python / python/typeshed

`functools.lru_cache` wrapped function with TypeVar has wrong return type.

未关闭
#6,987 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
5.1k
派生
2.1k
平均合并
1 天 19 小时
30 天内合并 PR
82

描述

Hi,

I think there is a problem when using functools.lru_cache (and functools.cache). When the decorated function uses a TypeVar for typing arguments and return type, the wrapped function returend by functools.lru_cache has wrong (or unresolved) types.
This is not the case when replacing the TypeVar with an explicit type. See the mwe below. Thx.

import functools
from typing import TypeVar

_T = TypeVar("_T")


def my_func(elem: _T) -> list[_T]:
    return [elem]
    
my_func_cached = functools.lru_cache(my_func)

a = my_func("a")
reveal_type(a)  # Revealed type is "builtins.list[builtins.str*]"
a_c = my_func_cached("a")

# ERROR: this should be "builtins.list*[builtins.str]"
reveal_type(a_c)  # Revealed type is "builtins.list*[_T`-1]"


# this works

def my_func_str(elem: str) -> list[str]:
    return [elem]
    
my_func_str_cached = functools.lru_cache(my_func_str)

a_str = my_func_str("a")
reveal_type(a_str)  # Revealed type is "builtins.list[builtins.str]"
a_str_c = my_func_str_cached("a")
reveal_type(a_str_c)  # Revealed type is "builtins.list*[builtins.str]"

Running:
Python 3.10.1
mypy 0.931
Linux 5.16.0-arch1-1

贡献指南

打开贡献指南

从这里开始

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

调研方向

使用 mypy 0.931 通过提供的最小示例重现该问题,然后检查 functools.lru_cache 和 functools.cache 的 typeshed 定义。当缓存的泛型函数显示 list[str] 而不是未解析的 TypeVar,同时显式的 str 示例仍能正常工作时,工作即告完成。

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

评估

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

把新 issue 发到你的邮箱

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