By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Function decorators in Python are a powerful tool that allows you to modify the behavior of a function or method. They are used extensively in web frameworks, logging, and access control. Understanding decorators is crucial for Python developers as they enhance code reusability and readability. Incorrect usage can lead to bugs that are hard to trace, affecting both functionality and performance. For instance, improperly applying a decorator might result in unintended side effects, such as incorrect logging or failed authentication checks.
python def simple_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper
Common Pitfall: ⚠️ Forgetting to call the original function inside the wrapper.
Apply Decorators Using @syntax
Example: ```python @simple_decorator def say_hello(): print("Hello!")
say_hello() ``` - Common Pitfall: ⚠️ Misunderstanding the order of execution in nested decorators.
Create Decorators with Arguments
python def decorator_with_args(decorator_arg1, decorator_arg2): def decorator(func): def wrapper(*args, kwargs): print("Decorator arguments:", decorator_arg1, decorator_arg2) return func(*args, kwargs) return wrapper return decorator
Common Pitfall: ⚠️ Incorrectly handling the arguments passed to the decorator.
Chain Multiple Decorators
Example: ```python def decorator1(func): def wrapper(): print("Decorator 1") func() return wrapper
def decorator2(func): def wrapper(): print("Decorator 2") func() return wrapper
@decorator1 @decorator2 def say_hello(): print("Hello!")
say_hello() ``` - Common Pitfall: ⚠️ Confusion about the order of execution in chained decorators.
Experts view decorators as a way to separate cross-cutting concerns from business logic. They think in terms of reusable components that can be applied across different functions, making the codebase more modular and maintainable. Instead of embedding repetitive code within functions, they encapsulate it within decorators.
Exam trap: Questions that require identifying why a function is not being executed.
The mistake: Not preserving the original function's metadata.
functools.wraps
Exam trap: Questions about function attributes and documentation.
The mistake: Incorrectly handling arguments in the wrapper function.
*args
kwargs
Exam trap: Questions that involve functions with varying arguments.
The mistake: Misunderstanding the order of execution in chained decorators.
Scenario: You need to log the execution time of a function.Question: Write a decorator that logs the execution time of any function it decorates.Solution: 1. Define a decorator that measures the execution time.2. Use the time module to record the start and end times.3. Print the execution time.
time
import time def execution_time_decorator(func): def wrapper(*args, kwargs): start_time = time.time() result = func(*args, kwargs) end_time = time.time() print(f"Execution time: {end_time - start_time} seconds") return result return wrapper @execution_time_decorator def sample_function(): time.sleep(2) sample_function()
Answer: The function will print the execution time.Why it works: The decorator wraps the original function, measures the time before and after execution, and prints the difference.
Scenario: You need to create a decorator that checks if a user is authenticated.Question: Write a decorator that checks if a user is authenticated before executing a function.Solution: 1. Define a decorator that checks for authentication.2. Use a global variable to simulate authentication status.3. Raise an exception if the user is not authenticated.
authenticated = True def authentication_decorator(func): def wrapper(*args, kwargs): if not authenticated: raise Exception("User is not authenticated") return func(*args, kwargs) return wrapper @authentication_decorator def access_sensitive_data(): print("Accessing sensitive data") access_sensitive_data()
Answer: The function will execute if the user is authenticated.Why it works: The decorator checks the authentication status before executing the function.
@decorator_name
functools
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.