Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

functools.wraps

Si applica alla funzione involucro interna quando si scrive un decoratore.

Versione: Python 3.14; repository image, production runtime not attested

Sintassi

@functools.wraps(wrapped)

Si applica alla funzione involucro interna quando si scrive un decoratore.

Usa update_wrapper per riferire nome, documentazione e altri metadati alla funzione avvolta. La chiamata esegue ancora l’involucro e __wrapped__ espone l’originale immediato per ispezione.

L’esempio stampa add, 8, 4.

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

Esempi

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))

Risultato

add 8 4

L’esempio stampa add, 8, 4.

Fonti