mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Mypy v1.10.0 errors out when functools wraps a method

Open davidbrochart opened this issue 1 year ago • 3 comments

Bug Report

mypy v1.10.0 gives the following error, while it was working with v1.9.0:

test.py:13: error: Missing positional argument "self" in call to "__call__" of "_Wrapped"  [call-arg]

To Reproduce

# test.py

from functools import wraps

class Foo:
    def f(self):
        pass

class Bar:
    @wraps(Foo.f)
    def f(self):
        pass

bar = Bar()
bar.f()
mypy test.py

Expected Behavior

There should be no error.

davidbrochart avatar Apr 24 '24 16:04 davidbrochart

almost certainly due to https://github.com/python/mypy/pull/16942

AlexWaygood avatar Apr 24 '24 17:04 AlexWaygood

I also hit this in a few places. Here's the relevant upstream bug https://github.com/python/typeshed/issues/10653

Workaround I used:

from typing import TYPE_CHECKING

class Bar:
    def f(self):
        pass

    if not TYPE_CHECKING:
        f = wraps(Foo.f)(f)

Hnasar avatar Apr 24 '24 17:04 Hnasar

I've also run into this. My workaround was to use update_wrapper() (for which wraps() is a convenience wrapper) instead. This is, understandably, completely invisible to Mypy.


from functools import update_wrapper

class Foo:
    def f(self):
        pass

class Bar:
    def f(self):
        pass
    update_wrapper(f, Foo.f)

bar = Bar()
bar.f()

broken-pen avatar Jun 11 '24 11:06 broken-pen

We hit this too. See: https://github.com/SciTools/iris/pull/6033

I guess this is the same problem, but it's not our only usage of "wraps", so I'm not really clear why other uses seem to be OK.

FWIW my workaround is to include an own-brew replacement for "wraps", based on the above hints :

# Use custom version of "wraps", to workaround MyPy v1.10 problem
# See : https://github.com/python/mypy/issues/17166
# TODO: remove when MyPy fixed
def wraps(x):
    def _inner(f):
        return update_wrapper(f, x)

    return _inner

pp-mo avatar Jul 23 '24 10:07 pp-mo