python / python/typeshed

functools.wraps does not work on class methods

Open
#10,653 9 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the minimal Python 3.11 reproduction with pyright and compare it with mypy. Then inspect the typeshed stub for functools.wraps, focusing on how it represents decorated functions and methods. Done means the class-method example type-checks and assert_type(instance.my_method(5), str) reports no errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.