Decorators in Python: Enhancing Functions with Style
Decorators are a powerful feature in Python that allow you to modify or enhance the behavior of functions. They provide a clean and concise way to wrap functions with additional functionality. In this tutorial, we’ll explore the basics of decorators and how to use them effectively.
1. What are Decorators?
In Python, a decorator is a design pattern that allows you to extend or modify the behavior of callable objects (functions or methods) without changing their actual code. Decorators are often used for tasks such as logging, timing, access control, or modifying the return value of a function.
2. Creating Simple Decorators
2.1. Basic Syntax
def my_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
@my_decorator
def say_hello():
print("Hello!")
# Calling the decorated function
say_hello()
In this example, my_decorator
is a simple decorator that wraps the say_hello
function. The wrapper
function is the additional functionality that gets executed before and after calling the original function.