Using @contextmanager in Odoo for Efficient Code Management

Muhammad Abdullah Arif
3 min readJun 10, 2024

In software development, maintaining clean, organized, and efficient code is essential, especially in large frameworks like Odoo. Python’s @contextmanager decorator from the contextlib module is a powerful tool that can help achieve this by managing setup and teardown processes around a block of code. In this blog post, we'll explore how to use @contextmanager in Odoo to ensure that certain operations are executed before and after a critical function, such as updating an order status.

What is @contextmanager?

The @contextmanager decorator allows you to define a function that will be used to set up and tear down a context for a block of code. This is particularly useful when you need to ensure that certain actions are taken before and after a particular operation, ensuring better resource management and cleaner code.

Example Usage in Odoo

Let’s consider a scenario where we want to perform some actions before and after updating the status of an order in Odoo. We’ll define a context manager that prints messages before and after the update process.

from contextlib import contextmanager

class SaleOrder(models.Model):
_inherit = 'sale.order'

@contextmanager
def before_and_after_update(self, order_id):
print("Before updating order status...")
yield
print("After updating order status...")

def update_order_status(self, order_id):
with…

--

--

Muhammad Abdullah Arif
Muhammad Abdullah Arif

Written by Muhammad Abdullah Arif

Python developer. The facts are the facts but opinions are my own.