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

Introducing functool.wraps

Pyyhkäise näyttääksesi valikon

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?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 4. Luku 7

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 4. Luku 7
some-alt