Repository navigation
How to use functools.wraps with method decorators #2128
Replies: 2 comments
|
I don't think there is a good solution. Callable protocols and their interaction with methods is fundamentally broken in Python currently. I think this will need a solution in the typing spec before we can make any changes in typeshed. |
|
One workaround that still uses the standard library: call from collections.abc import Callable
from functools import update_wrapper
def trace[**P, T](f: Callable[P, T]) -> Callable[P, T]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
return f(*args, **kwargs)
update_wrapper(wrapper, f)
return wrapperI checked this with mypy 2.4.1 in strict mode: decorating a method preserved the bound |
Uh oh!
There was an error while loading. Please reload this page.
Say I have a noop decorator:
Great. Now let's replace
Callablewith a Protocol defining__call__, say if we want to accessfunc.__name__or access specific args/kwargs being passed in:This fails on mypy with
Per #1040, we should add
__get__to return a Protocol with the post-bound signature:Now this fails with:
It works if I comment out
@functools.wraps(). For now, we can workaround it withAll reactions