Py Decorators — Free Python Tutorial
Learn Py Decorators in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Py Decorators in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Py Decorators in Python
A decorator is a function that wraps another function to add extra behaviour without modifying the original function code. It's Python's clean way to extend function behaviour.
Decorators use the @ symbol before a function definition. Under the hood, @my_decorator is the same as my_function = my_decorator(my_function).
Common uses: logging function calls, timing how long a function takes, checking authentication, repeating/retrying operations.
The functools.wraps decorator should be used inside your decorator to preserve the original function's name and docstring.
Py Decorators — Syntax
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# code BEFORE calling func
result = func(*args, **kwargs)
# code AFTER calling func
return result
return wrapper
@my_decorator
def my_function():
...
Learn Py Decorators step by step with Syllab's free interactive Python tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Python course →