In Python, developers have a handy option called wrapper functions or decorators. These tools allow them to add extra functionality to their functions without diving into the source code. This approach encourages code reuse and maintainability.
What are Wrapper Functions/Decorators?
Wrapper functions, or decorators, act like helpful assistants for functions. They take a function as input, work their magic, and produce an enhanced version of it as output. This enables you to boost a function's capabilities without having to change its core code, which in turn promotes code reusability and maintainability.
Odoo's decorators are a useful way to enhance the functionality of a model or method without changing the actual code. They are a powerful tool for customizing and extending Odoo to meet the specific needs of businesses. So, in this blog, we will discuss how we can create a custom Decorator in Odoo.
1. Create a Python File for the Decorator
Here, I'm creating a new directory called "utilities" to define the decorator.
Inside the utility directory, create a new Python file (e.g., util.py) where you will define your custom decorator.
2. Define the Decorator
Define your decorator function within the util.py file. Here's an example of a simple decorator.
def wrapper_decorator(func):
"""
Decorator that reports the execution time.
"""
def modified_function(*args, **kwargs):
# Do something before calling the original function
print("Before calling the original function")
# Call the original function
result = func(*args, **kwargs)
# Do something after calling the original function
print("After calling the original function")
return result
return modified_function
Don't forget to define these sub-modules in __init__.py to make them part of the public interface.
from .util import wrapper_decorator
3. Use the Decorator
Now, we can use our custom decorator in our function.
from odoo import fields, models
from odoo.addons.utilities import wrapper_decorator
class YourModel(models.Model):
_name = 'your.model'
@wrapper_decorator
def my_function(self):
# Method logic here
pass
In this example, the wrapper_decorator acts as a wrapper function or decorator. It takes another function, my_function, as input. Inside the wrapper_function, it performs actions before and after calling the my_function.
The syntax @wrapper_decorator is a way to apply the decorator to my_function.
When my_function is invoked, it's actually the wrapper_function that gets executed. It starts by printing "Before calling the original function" and then proceeds to call my_function (which performs your method logic). Finally, it prints "After calling the original function."
This approach allows you to enhance or modify the behavior of my_funciton without altering its code. They provide a means of extending function functionality in a reusable manner.