- Returns True if the object matches; otherwise False.
- Preferred over type(obj) is SomeClass because it supports class inheritance.
✅ Syntax
isinstance(obj, Class) # Single class
isinstance(obj, (Class1, Class2)) # Any of multiple classes
📌 Basic Python Example
isinstance(5, int) # ➝ True
isinstance(“Odoo”, (int, str)) # ➝ True
isinstance([], dict) # ➝ False
🧠 Realistic Use Case in Odoo
1. Verify Model Type Before Processing
def process_record(record):
if not isinstance(record, models.BaseModel):
raise ValueError(“Expected an Odoo record.”)
# Safe to access record methods/fields
2. Distinguish Between Recordsets and Single Records
from odoo import models
def ensure_single(recordset):
if not isinstance(recordset, models.Model):
raise ValueError(“Invalid input”)
if len(recordset) != 1:
raise ValueError(“Expected exactly one record”)
ensure_single(self.env[‘res.partner’].browse(1))
3. Handle Different Field Value Types
value = self.some_field
if isinstance(value, bool):
# handle boolean
elif isinstance(value, (int, float)):
# handle numeric
else:
# handle other types
✅ Summary Table
Use Case |
isinstance() Benefits |
| Model-type validation | Ensures robust method inputs |
| Multi-class checks | Pass tuple for OR-type validation |
| Supports inheritance | True for subclasses and base classes |