Decorators in Python @decorator is an important Python topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Decorators in Python @decorator solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Decorators in Python @decorator should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Decorators in Python @decorator should be studied as a practical Python lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the python > decorators page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
A decorator is a function that wraps another function to extend or modify its behavior - without changing the original function's code. They use the @ syntax.
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before the function")
result = func(*args, **kwargs)
print("After the function")
return result
return wrapper
# Apply with @ syntax
@my_decorator
def say_hello(name: str):
print(f"Hello, {name}!")
say_hello("Alice")
# Before the function
# Hello, Alice!
# After the function
# Equivalent to:
# say_hello = my_decorator(say_hello)
from functools import wraps
def my_decorator(func):
@wraps(func) # preserves __name__, __doc__, etc.
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@my_decorator
def greet(name: str) -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
print(greet.__name__) # greet (not 'wrapper')
print(greet.__doc__) # Greet someone by name.
import time
from functools import wraps
# Timer decorator
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} took {end - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(0.1)
return "done"
slow_function() # slow_function took 0.1001s
# Logger decorator
def log_calls(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}({args}, {kwargs})")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_calls
def add(a: int, b: int) -> int:
return a + b
add(3, 5)
# Calling add((3, 5), {})
# add returned 8
# Retry decorator
def retry(times: int = 3):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {attempt} failed: {e}")
raise RuntimeError(f"Failed after {times} attempts")
return wrapper
return decorator
@retry(times=3)
def unstable_api():
import random
if random.random() < 0.7:
raise ConnectionError("Network error")
return "Success"
from functools import wraps
def bold(func):
@wraps(func)
def wrapper(*args, **kwargs):
return f"<b>{func(*args, **kwargs)}</b>"
return wrapper
def italic(func):
@wraps(func)
def wrapper(*args, **kwargs):
return f"<i>{func(*args, **kwargs)}</i>"
return wrapper
# Applied bottom-up: italic first, then bold
@bold
@italic
def greet(name: str) -> str:
return f"Hello, {name}!"
print(greet("Alice")) # <b><i>Hello, Alice!</i></b>
# Class-based decorator
class Cache:
def __init__(self, func):
wraps(func)(self)
self.func = func
self._cache = {}
def __call__(self, *args):
if args not in self._cache:
self._cache[args] = self.func(*args)
return self._cache[args]
@Cache
def fibonacci(n: int) -> int:
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(35)) # fast due to caching
When studying Decorators in Python @decorator, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Python, Decorators in Python @decorator becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
def review_decorators-in-python-decorator():
value = "sample"
if value:
print("Decorators in Python @decorator: normal path is ready")
else:
print("Decorators in Python @decorator: handle the empty path first")
review_decorators-in-python-decorator()
items = []
if not items:
print("Decorators in Python @decorator: no data available, show a fallback")
else:
print(items[0])
Memorizing Decorators in Python @decorator without the situation where it is useful.
Connect Decorators in Python @decorator to a concrete Python task.
Testing Decorators in Python @decorator only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Decorators in Python @decorator.
Memorizing Decorators in Python @decorator without the situation where it is useful.
Connect Decorators in Python @decorator to a concrete Python task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Python, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.