
Python
Decorators are functions that modify other functions. Think of them like wrapping paper around a gift — they enhance what's inside without changing it.
A decorator is a function that takes another function as input and returns a modified version of it. The magic is that the original function's code never changes—the decorator just wraps it with extra functionality. This is useful when you want to add features like logging, timing, or authentication to multiple functions without editing each function individually.
def my_decorator(func):
def wrapper():
print("Before the function")
func()
print("After the function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function
# Hello!
# After the functionWhen you use the `@decorator` syntax, Python automatically takes your function and passes it to the decorator function. The decorator returns a modified version, and that becomes your new function. It's just syntactic sugar—a convenient shorthand that makes decorators readable and intuitive. Without the `@` symbol, you'd have to manually wrap your function, which is more verbose.
@my_decorator
def say_hello():
print("Hello!")
# Is the same as:
def say_hello():
print("Hello!")
say_hello = my_decorator(say_hello)def log_calls(func):
def wrapper(*args):
print(f"Calling {func.__name__}")
func(*args)
return wrapper
@log_calls
def greet(name):
print(f"Hello {name}!")
greet("Alice")
# Output:
# Calling greet
# Hello Alice!def repeat(func):
def wrapper():
func()
func()
func()
return wrapper
@repeat
def say_hi():
print("Hi!")
say_hi()
# Output:
# Hi!
# Hi!
# Hi!1. Decorators are functions that take a function
2. They return a modified version of the function
3. Use `@decorator_name` above the function
4. Decorators add behavior without changing the original
| Concept | Remember |
|---|---|
| Decorator | Function that wraps another function |
| @ symbol | Shorthand for applying a decorator |
| Purpose | Add behavior without changing code |
| Example | Logging, timing, repeating, etc. |
Now let's explore functional programming with map, filter, and reduce!
Next: Functional Programming →
Ready to practice? Try challenges or view solutions
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward