Decorators & higher-order functions
Functions can be passed around as values. A decorator wraps a function to add behavior. functools.wraps preserves the wrapped function’s metadata. Start with a small wrapper before using complex decorators.
हिन्दी में समझें
फ़ंक्शन मान की तरह भेजे जा सकते हैं। डेकोरेटर फ़ंक्शन को लपेटकर व्यवहार जोड़ता है। functools.wraps मूल फ़ंक्शन की जानकारी सुरक्षित रखता है।
अभ्यास: wrapper में लिपटे फ़ंक्शन के बाद print("Finished") जोड़ें।
Hinglish mein samjhein
Functions ko values ki tarah pass kar sakte hain. Decorator function ko wrap karke behavior jodta hai. functools.wraps original metadata preserve karta hai.
Practice: wrapper ke andar wrapped function call ke baad print("Finished") jodo.
A small Python example
from functools import wraps
def announce(fn):
@wraps(fn)
def wrapper():
print("Starting")
return fn()
return wrapper
@announce
def hello():
print("Hello")
hello()The browser playground runs real Python with Pyodide. Use sample variables instead of interactive input(). Browser package support differs from desktop Python.
Try this example in the Python playground →Practise this idea
Add print("Finished") after the wrapped function call inside wrapper.
Check answer & explanation
from functools import wraps
def announce(fn):
@wraps(fn)
def wrapper():
print("Starting")
result = fn()
print("Finished")
return result
return wrapper
@announce
def hello():
print("Hello")
hello()A return exits a function immediately. Store the wrapped function result, print Finished, and only then return the stored result.
Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.
Check your understanding
A decorator usually…
Check the quiz answer
Wraps a function
Decorators take a callable and return a replacement or wrapper.
References & corrections
Use the official Python documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.