Junior — Middle
How to implement a decorator in Python so that the original function remains accessible for calls?
sobes.tech AI
Answer from AI
To keep the original function accessible after applying a decorator, you can save a reference to it as an attribute of the wrapper. Often, functools.wraps is used for this purpose, which copies metadata and preserves a reference to the original in the __wrapped__ attribute.
Example:
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before calling the function")
result = func(*args, **kwargs)
print("After calling the function")
return result
return wrapper
@my_decorator
def greet(name):
print(f"Hello, {name}!")
# Calling the decorated function
greet("World")
# Access to the original function
original = greet.__wrapped__
original("World")
Thus, greet.__wrapped__ is the original function without the decorator.