Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Introducing functool.wraps | Mastering Python Decorators
Functional Programming Concepts in Python

Introducing functool.wraps

Scorri per mostrare il menu

When you write your own decorators, you often lose important information about the original function, such as its name, docstring, and module. This happens because the decorator replaces the original function with a new wrapper function. To fix this, use the functools.wraps decorator from Python's standard library.

By applying functools.wraps to your wrapper function, you preserve the original function's metadata. This means:

  • The function's __name__ attribute remains the same as the original;
  • The function's __doc__ string is kept intact;
  • The __module__ attribute and other metadata are preserved.

Preserving metadata is important for debugging, documentation generation, and tools that rely on function introspection. Without functools.wraps, stack traces and help utilities may display confusing or incorrect information, making your code harder to maintain and debug.

1234567891011121314151617181920212223
from functools import wraps # Define a decorator that will wrap another function def my_decorator(func): # Use @wraps to preserve metadata from the original function @wraps(func) def wrapper(*args, **kwargs): # This code runs before the original function print("Running the decorated function...") return func(*args, **kwargs) # Call the original function return wrapper # Return the wrapper as the new decorated function # Apply the decorator to a function def say_hello(): """Prints a hello message.""" print("Hello!") say_hello = my_decorator(say_hello) say_hello() # Print out the preserved metadata print(f"Function name: {say_hello.__name__}") # Name is preserved print(f"Docstring: {say_hello.__doc__}") # Docstring is preserved

You can see how to use functools.wraps to preserve the original function's metadata when creating a decorator. By applying functools.wraps to your wrapper, you ensure that attributes like the function's name and docstring are not lost after decoration.

question mark

Why is it important to use functools.wraps when writing decorators in Python?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 7

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 4. Capitolo 7
some-alt