Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

functools.wraps

Decorates a wrapper so that common metadata identifies the wrapped callable.

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

Syntax

@functools.wraps(wrapped)

Decorates a wrapper so that common metadata identifies the wrapped callable.

The preserved original-function reference permits inspection or a direct call that bypasses the wrapper.

Apply wraps to the inner wrapper when writing a decorator. It adapts update_wrapper so name, documentation and other selected metadata identify the wrapped function. The wrapper remains the callable being executed; __wrapped__ exposes the immediate original and allows introspection to follow it. The sample prints 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

Examples

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

Result

add 8 4

Apply wraps to the inner wrapper when writing a decorator. It adapts update_wrapper so name, documentation and other selected metadata identify the wrapped function. The wrapper remains the callable being executed; `__wrapped__` exposes the immediate original and allows introspection to follow it. The sample prints add, 8, 4.

Sources