How to Invoke Python Functions from XML Files in Odoo 19: Complete Developer Guide
By Braincuber Team
Published on December 14, 2025
Looking to automate tasks during Odoo 19 module installation? The XML <function> tag is your solution. This comprehensive guide explains how to invoke Python functions directly from XML files in Odoo 19, enabling you to execute custom logic, create records, and perform initialization tasks automatically when your module is installed or updated.
What You'll Learn:
- How to set up XML data files for function invocation
- Calling Python methods without arguments from XML
- Passing parameters to Python functions via XML
- Best practices for production-ready implementations
- Real-world use cases and examples
Why Invoke Python Functions from XML in Odoo 19?
Odoo's XML-based architecture provides a powerful, declarative approach to defining data models and user interfaces. However, there are scenarios where static XML definitions fall short—particularly when dealing with:
- Dynamic data initialization - Creating records based on complex business logic
- Large or changing datasets - Populating data that can't be hardcoded
- Post-installation updates - Modifying existing records when a module is installed
- Automated setup procedures - Running initialization scripts without manual intervention
- Data migration tasks - Transforming or updating data during module upgrades
The XML <function> tag bridges this gap by allowing you to invoke Python methods at install time, ensuring necessary updates or initialization steps occur automatically during module installation.
Step 1: Setting Up Your XML Data File
To trigger a Python method from an XML file in Odoo 19, you first need to create an XML data file. This file serves as the blueprint for operations that should run automatically when the module is installed.
Create a file named data/init_data.xml in your module directory:
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<data noupdate="1">
<!-- Your function calls and data will go here -->
</data>
</odoo>
Understanding the noupdate Attribute
The noupdate attribute is crucial for controlling when your data and functions are executed:
| Value | Behavior | Use Case |
|---|---|---|
noupdate="1" |
Data is NOT re-imported on module updates | Demo data, initial setup, one-time operations |
noupdate="0" |
Data is re-imported on every module update | Configuration data that must stay synchronized |
Important: Don't forget to reference your XML file in your module's __manifest__.py file under the data key to ensure it's loaded during installation.
Method 1: Calling a Function Without Arguments
The simplest way to invoke a Python function from XML is without passing any arguments. This is useful for initialization tasks that don't require external input.
XML Configuration
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<data noupdate="1">
<function model="res.partner" name="_create_default_partner"/>
</data>
</odoo>
In this example:
model="res.partner"- Specifies which Odoo model contains the methodname="_create_default_partner"- The name of the Python method to invoke
Python Implementation
Create a Python file that inherits the target model and implements the method:
# -*- coding: utf-8 -*-
from odoo import api, models
class ResPartner(models.Model):
_inherit = "res.partner"
@api.model
def _create_default_partner(self):
"""
Function invoked from XML during module installation.
Creates a default partner record for initial setup.
"""
# Check if partner already exists to avoid duplicates
existing = self.search([('name', '=', 'Default Partner')], limit=1)
if not existing:
self.create({
'name': 'Default Partner',
'is_company': True,
'customer_rank': 1,
})
return True
return False
Best Practice: Always check for existing records before creating new ones to prevent duplicate data when the module is reinstalled.
Method 2: Calling a Function With Arguments
For more dynamic scenarios, you can pass arguments to your Python function using the <value> tag within the <function> element.
XML Configuration with Parameters
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<data noupdate="1">
<function model="res.partner" name="_create_partner_with_name">
<value>Braincuber Technologies</value>
</function>
</data>
</odoo>
The <value> tag contains the argument that will be passed to the Python method. You can include multiple <value> tags for functions that accept multiple parameters.
Python Implementation with Parameters
# -*- coding: utf-8 -*-
from odoo import api, models
class ResPartner(models.Model):
_inherit = "res.partner"
@api.model
def _create_partner_with_name(self, partner_name):
"""
Function invoked from XML with a name parameter.
Creates a partner record using the provided name.
Args:
partner_name (str): The name for the new partner record
Returns:
recordset: The created partner record
"""
# Validate input
if not partner_name:
return False
# Check for existing partner
existing = self.search([('name', '=', partner_name)], limit=1)
if existing:
return existing
# Create new partner
return self.create({
'name': partner_name,
'is_company': True,
'customer_rank': 1,
})
Advanced Example: Multiple Parameters
You can pass multiple arguments to a function by including multiple <value> tags:
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<data noupdate="1">
<function model="res.partner" name="_create_company_partner">
<value>Braincuber Technologies</value>
<value>contact@braincuber.com</value>
<value>+1-555-123-4567</value>
</function>
</data>
</odoo>
@api.model
def _create_company_partner(self, name, email, phone):
"""
Create a company partner with full contact details.
Args:
name (str): Company name
email (str): Contact email
phone (str): Contact phone number
"""
existing = self.search([('email', '=', email)], limit=1)
if not existing:
return self.create({
'name': name,
'email': email,
'phone': phone,
'is_company': True,
'customer_rank': 1,
})
return existing
Real-World Use Cases
Here are practical scenarios where invoking functions from XML proves invaluable:
🏢 Initial Data Setup
Create default records like company settings, payment terms, or product categories during module installation.
🔄 Data Migration
Transform or update existing records when upgrading from older module versions.
⚙️ Configuration Automation
Set up system parameters, email templates, or automated actions automatically.
🔗 External Integration Setup
Initialize API connections, webhook configurations, or third-party service credentials.
Best Practices for Production
- Always use @api.model decorator - Functions called from XML should be model-level methods
- Implement idempotency - Check for existing records before creating to prevent duplicates
- Add proper error handling - Use try-except blocks to handle potential failures gracefully
- Document your functions - Include docstrings explaining what the function does and its parameters
- Use noupdate wisely - Set to "1" for one-time operations, "0" for data that must stay synchronized
- Test thoroughly - Test both fresh installations and module upgrades
- Log important operations - Use
_loggerto track function execution
Complete Module Example
Here's a complete example showing the module structure:
# __manifest__.py
{
'name': 'Custom Partner Setup',
'version': '19.0.1.0.0',
'category': 'Tools',
'summary': 'Automated partner setup on installation',
'depends': ['base'],
'data': [
'data/init_data.xml',
],
'installable': True,
'auto_install': False,
}
Frequently Asked Questions
Can I call functions from multiple models in one XML file?
Yes, you can include multiple <function> tags targeting different models within the same XML file.
What happens if the function fails?
If a function raises an exception, the module installation will fail. Always implement proper error handling to prevent this.
Can I pass complex data types as arguments?
The <value> tag primarily supports strings. For complex data, consider using eval attribute or storing configuration in separate records.
Conclusion
The <function> tag in Odoo 19 XML files provides a clean, declarative way to execute Python methods during module installation or updates. Whether you're initializing data, migrating records, or automating configuration, this technique ensures your operations run reliably and automatically.
By combining XML declarations with custom Python logic, you can build modules that are self-configuring and production-ready from the moment they're installed.
Need Expert Odoo Development Help?
Our team specializes in custom Odoo module development, data migration, and ERP implementation. Let us help you build robust, automated solutions for your business.
