functools.wraps does not work on class methods
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 5.1k
- 分支
- 2.1k
- 平均合併
- 1 天 19 小時
- 30 天內合併 PR
- 82
描述
We recently hit an error using @wraps on a class method in Trio: https://github.com/python-trio/trio/issues/2775#issuecomment-1702892474 when checked with pyright. It works fine on mypy, but I'm guessing they might be special-casing wraps usage while pyright doesn't.
Minimal repro (python 3.11):
from functools import wraps
from typing import assert_type
def foo(param: int) -> str:
"""docstring"""
return ""
@wraps(foo)
def my_function(blah: int) -> str:
return 'foo'
# works fine
assert_type(my_function(5), str)
class MyOtherClass:
def bar(self, param: int) -> str:
"""docstring"""
return ""
class MyClass:
@wraps(MyOtherClass.bar)
def my_method(self, blah: int) -> str:
return 'foo'
instance = MyClass()
# works in mypy, but not pyright
assert_type(instance.my_method(5), str)
mypy 1.5.1 works without any issue, pyright 1.1.325 gives
./test.py
./test.py:26:13 - error: Argument missing for parameter "blah" (reportGeneralTypeIssues)
./test.py:26:13 - error: "assert_type" mismatch: expected "str" but received "Unknown" (reportGeneralTypeIssues)
2 errors, 0 warnings, 0 informations
This smells a lot like the problem with getting functools.cache to work both with methods and functions, see e.g. https://github.com/python/typeshed/issues/6347
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
首先使用 pyright 執行最小的 Python 3.11 重現,並將其與 mypy 比較。接著檢查 functools.wraps 的 typeshed stub,著重了解它如何表示經裝飾的函式與方法。當類別方法範例通過型別檢查,且 assert_type(instance.my_method(5), str) 未回報任何錯誤時,即表示完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- devtools
- Issue 類型
- 缺陷
- 難度
- 4/5
- 預估耗時
- 3-5 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100