Interview question
What does functools.wraps do and why is it important in decorators? functools.wraps क्या करता है और decorators में यह क्यों important है?
Answer
Without functools.wraps, a decorated function loses its original name, docstring, and metadata, since the wrapper function replaces it entirely. wraps() copies this metadata onto the wrapper.
def my_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def greet(name):
"""Greets a person by name."""
print(f'Hello, {name}')
print(greet.__name__) # 'wrapper' - WRONG, lost the original name!
print(greet.__doc__) # None - lost the docstring!
# FIX using functools.wraps
from functools import wraps
def my_decorator_fixed(func):
@wraps(func) # copies __name__, __doc__, and other metadata from func
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator_fixed
def greet2(name):
"""Greets a person by name."""
print(f'Hello, {name}')
print(greet2.__name__) # 'greet2' - correct!
print(greet2.__doc__) # 'Greets a person by name.' - correct!
# Why it matters: debugging, introspection tools, documentation generators
# (like Sphinx) and help() all rely on accurate __name__ and __doc__
help(greet2) # shows accurate info because of @wrapsfunctools.wraps के बिना, decorated function अपना original name, docstring, metadata खो देता है क्योंकि wrapper function उसे पूरी तरह replace कर देता है। wraps() यह metadata wrapper पर copy करता है।
def my_decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def greet(name):
"""नाम से greet करता है।"""
print(f'Hello, {name}')
print(greet.__name__) # 'wrapper' - गलत!
print(greet.__doc__) # None - docstring खो गई!
# functools.wraps से FIX
from functools import wraps
def my_decorator_fixed(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator_fixed
def greet2(name):
"""नाम से greet करता है।"""
print(f'Hello, {name}')
print(greet2.__name__) # 'greet2' - सही!
print(greet2.__doc__) # सही!Was this answer clear?