How to Implement **kw in Odoo?
In Odoo development, we often create reusable, dynamic, and modular code. Python’s **kw (short for **kwargs) feature plays a significant role in achieving this flexibility. It allows functions or methods to accept an arbitrary number of keyword arguments, making them highly adaptable and forward-compatible.
What is **kw?
In Python, **kw (short for **kwargs) captures extra keyword arguments as a dictionary.
In Odoo, it's often used in method overrides to support dynamic or future arguments without breaking compatibility.
Scenario: Overriding _prepare_invoice in sale.order
Odoo’s core methods may evolve to include new keyword arguments. Using **kw ensures your override won't break when those changes occur.
from odoo import models
class SaleOrder(models.Model):
_inherit = 'sale.order'
def _prepare_invoice(self, **kw):
res = super()._prepare_invoice(**kw)
res.update({
'custom_note': 'Invoice generated from custom logic',
})
return res
Why use **kw here?
- Your method stays compatible even if Odoo adds arguments like order_lines=None in the future.
- Prevents TypeError due to unexpected keyword arguments.
Other Use Case: Utility Method with Optional Behavior
def process_action(self, **kw):
if kw.get('auto_confirm'):
self.action_confirm()
if kw.get('send_email'):
self._notify_customer()
You can call the method with dynamic behavior:
order.process_action(auto_confirm=True, send_email=False)
✅ Summary
Feature | Purpose |
**kw in Odoo | Captures extra keyword args to maintain method flexibility |
Use case | Method overrides, dynamic behavior, utility functions |
Benefit | Future-proof, readable, and extendable code |