CKTIS / Python
functools.wraps
Wordt bij het schrijven van een decorator op de binnenste wrapperfunctie toegepast.
Versie: Python 3.14; repository image, production runtime not attested
Syntax
@functools.wraps(wrapped)Wordt bij het schrijven van een decorator op de binnenste wrapperfunctie toegepast.
Gebruikt update_wrapper zodat naam, documentatie en andere metadata de omhulde functie identificeren. Een aanroep voert nog de wrapper uit en __wrapped__ toont het directe origineel voor inspectie.
Het voorbeeld drukt add, 8, 4 af.
from functools import wraps
from inspect import signature
def outer(f):
@wraps(f)
def wrapped(*args, **kw):
return 2 * f(*args, **kw)
return wrapped
@outer
def inc(x: int): return x+1
assert inc.__name__ == "inc" and str(signature(inc)) == "(x: int)"
assert inc(3) == 8 and inc.__wrapped__(3) == 4
Voorbeelden
import functools
def twice(func):
@functools.wraps(func)
def wrapper(n): return 2 * func(n)
return wrapper
@twice
def add(n): return n + 1
print(add.__name__, add(3), add.__wrapped__(3))
Resultaat
add 8 4
Het voorbeeld drukt add, 8, 4 af.