`functools.lru_cache` wrapped function with TypeVar has wrong return type.
オープン
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 5.1k
- フォーク
- 2.1k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 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
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
提供された最小限の例を mypy 0.931 で使って問題を再現し、その後 functools.lru_cache と functools.cache の typeshed 定義を調査します。キャッシュされたジェネリック関数が未解決の TypeVar ではなく list[str] を示し、明示的な str の例が引き続き動作すれば作業は完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- tooling
- issue の種類
- バグ
- 難易度
- 3/5
- 見積もり時間
- 1〜2日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100