Welcome to our deep dive into Python Decorators! In this lesson, we'll learn how to enhance your Python functions with decorators, making your code more readable, maintainable, and powerful.
Decorators are special syntactic constructs in Python that allow you to add extra functionality to existing functions and classes without modifying their source code. They are a fantastic tool for organizing and structuring your code, and they help improve code readability and reusability.
A decorator is defined using the @ symbol followed by the decorator function. Here's the basic syntax:
@decorator_function
def function_to_be_decorated():
# function code hereWhen the decorated function is called, Python first executes the decorator function, and then the original function.
Let's create a simple decorator to log the execution time of a function:
def log_execution_time(function):
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = function(*args, **kwargs)
end_time = time.time()
print(f"Execution time for {function.__name__}: {end_time - start_time} seconds")
return result
return wrapper
@log_execution_time
def example_function():
time.sleep(2) # Simulate some work
print("Example function executed!")Run the above code, and you'll see that example_function now logs the time it takes to execute.
There are two types of decorators in Python:
Function Decorators: Decorators for functions. We've already seen an example of this.
Class Decorators: Decorators for classes. We'll explore this type in a future lesson.
Decorators are useful in various scenarios, such as:
What is the purpose of a decorator in Python?
That's it for our Python Decorators lesson! In the next lesson, we'll dive into more advanced decorator topics and practical use cases. Happy coding! 🚀