Beginner LevelPython
What is a Python Decorator and how does the @decorator syntax work?
❓ Interview Prompt: Explain Higher-Order Functions, wrapping functions, `@functools.wraps`, and modifying function behavior dynamically.
A Decorator is a function that takes another function as an argument, extends or modifies its behavior, and returns a new function without changing the original function's source code:
The '@decorator' Syntactic Sugar:
'@my_decorator' placed above 'def foo():' is equivalent to: 'foo = my_decorator(foo)'.
•
'@functools.wraps(func)': Crucial helper applied to the inner wrapper function to preserve the original function's name and docstring!
Code Implementation Example
python
import functools
import time
def timer_decorator(func):
@functools.wraps(func) # Preserves original function __name__ and __doc__
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f'{func.__name__} executed in {round(time.time() - start, 4)}s')
return result
return wrapper
@timer_decorator
def process_data():
time.sleep(0.1)
process_data()💡Building a custom timing decorator with functools.wraps.
🎯 Interview Key Takeaway
Decorators modify function behavior dynamically. Always use @functools.wraps(func) on wrapper functions to preserve function metadata.
#Decorators#@functools.wraps#Higher-Order Functions#Beginner
Back to all Python Questions→