Python Decorators made easy
Python decorators are a powerful tool that allow you to modify the behavior of a function or class without changing its code. They’re especially useful for adding functionality to existing code, such as logging, timing, or validation. In this blog post, we’ll take a look at how to use decorators in Python, in a very easy way.
1. What are Decorators?
Decorators are essentially wrapper functions that modify the behavior of another function. They’re defined using the @
symbol, followed by the name of the decorator function. Here's a simple example:
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
2. Creating Decorators
To create a decorator, you simply define a function that takes another function as an argument and returns a new function that wraps the original function. The wrapper function can then modify the behavior of the original function in any way you like. Here’s another example:
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with arguments {args} and keyword arguments {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@log_function_call
def multiply(a, b):
return a * b
multiply(2, 3)
Output:
Calling multiply with arguments (2, 3) and keyword arguments {}
multiply returned 6
3. Decorating Classes
You can also decorate classes in Python using decorators. To do this, you simply create a decorator that takes a class as an argument and returns a modified version of the class. Here’s an example:
def uppercase_class_name(cls):
cls.__name__ = cls.__name__.upper()
return cls
@uppercase_class_name
class MyClass:
pass
print(MyClass.__name__)
Output: MYCLASS
4. Conclusion
Decorators are a powerful tool for adding functionality to existing code in Python. Whether you’re adding logging, timing, or validation, decorators can help you keep your code clean and maintainable. With a little practice, you’ll be able to create decorators that solve all sorts of problems in your code. So start experimenting today and see what you can do!