Python Expressions in Data and Views
Status: complete (crates/erp-expr).
Implements: ADR 0004 (language selection), ADR 0009 §9 (expression evaluator), ADR 0020 (Python expression sandbox).
Specs: docs/specs/data/data-views-api.md (SPEC-DATA-012, SPEC-DATA-054).
The erp-expr crate provides a pure, zero-I/O sandboxed expression evaluator for the subset of
Python syntax used throughout Odoo data files and views. It evaluates XML eval="..." attributes,
search="..." domains and context dictionaries under fixed resource limits and checked arithmetic.
View modifiers (invisible, readonly, required) are combined as text during view inheritance
(see below).
Where expressions are used
Section titled “Where expressions are used”Expressions are evaluated when data files are loaded (install and upgrade) and wherever a host evaluates an expression it stores:
-
XML data files (
<field eval="...">): computed values, relational commands, dates and configuration tuples:<field name="active" eval="True"/><field name="sequence" eval="10 + 5"/><field name="date_deadline" eval="(datetime.today() + relativedelta(months=1)).strftime('%Y-%m-%d')"/><field name="tag_ids" eval="[Command.set([ref('tag_urgent'), ref('tag_review')])]"/> -
Context dictionaries: default values or flags for actions and relational fields:
<field name="context" eval="{'default_partner_id': ref('base.main_partner'), 'search_default_my': 1}"/> -
Search domains (
domain="[...]"): Odoo domain lists of(field, operator, value)tuples:<field name="partner_id" domain="[('is_company', '=', True), ('parent_id', '=', False)]"/> -
View modifiers (
invisible="...",readonly="...",required="..."): conditions on the record’s values in forms and lists:<field name="reason" invisible="state != 'rejected'" required="state == 'rejected'"/>
Supported syntax and operators
Section titled “Supported syntax and operators”The evaluator implements a subset of Python expression grammar; it never executes statements or imports code:
- Literals:
True,False,None; 64-bit signed integers and floats; single- and double-quoted strings with escape sequences; f-strings; lists, tuples and dictionaries. - Operators:
- arithmetic
+,-,*,/,//,%,**, unary+,-and~; - comparisons
==,!=,<,<=,>,>=, including chained comparisons (0 < x < 10); - identity and membership
is,is not,in,not in; - boolean
and,or,not(short-circuiting); - bitwise
&,|,^,<<,>>.
- arithmetic
- Access: subscripts and slices (
items[0],name[:3]), attribute and method access on the values the host binds (dates,Command, records the data loader provides). - Conditionals and comprehensions:
a if condition else b, list comprehensions ([x * 2 for x in values if x]), generator expressions (sum(x for x in values)), and:=.
Not supported (refused with a parse error that names the construct): set literals, set and dict
comprehensions, ** unpacking in dict displays, lambda, import and other statement keywords.
Built-in functions and names
Section titled “Built-in functions and names”EvalContext::standard() binds the Python builtins and the names of Odoo’s data-loader context.
It deliberately binds nothing that reads host data:
-
Builtins:
str,repr,int,float,bool,len,list,tuple,dict,min,max,sum,abs,round. -
Relational commands (
Command), matching Odoo’sCommandnamespace for x2many writes:Command.create({'name': 'Item'}): create a child record (triple(0, 0, values))Command.update(id, {'name': 'New'}): update a child record (triple(1, id, values))Command.delete(id): delete the record (triple(2, id, 0))Command.unlink(id): remove from the relation without deleting (triple(3, id, 0))Command.link(id): add an existing record (triple(4, id, 0))Command.clear(): remove all relations (triple(5, 0, 0))Command.set([id1, id2]): replace the relation set (triple(6, 0, [ids]))
-
Date and time:
datetime(also bound asDateTime) is the datetime class: call it to build a value (datetime(2026, 1, 2)) or usedatetime.now()anddatetime.today(); it has no other attributes, sodatetime.date(...)anddatetime.timedelta(...)are refused.timedelta(days=1)andrelativedelta(months=1)are top-level names, andtime.strftime('%Y')formats the current time.now(),today()andtime.strftime()need a clock; the standard context has none and refuses them with aValueErrorthat says so. The data loader supplies the clock. -
Host-provided names: the data loader (
crates/erp-data/src/load/expr.rs) adds the clock,version, and host hooks that resolveref('module.xmlid')through its XML-id resolver (which reports a missing id) and answer record, search and group lookups. Record access throughobjandenvneedsEvalContext::with_model. Where the host has not provided them,ref,obj,env,user,has_groupandversionraise aNameErrorthat names the provider instead of returning an empty value.
View modifiers and dynamic attributes
Section titled “View modifiers and dynamic attributes”An inheriting view changes a modifier with position="attributes". To add or remove a condition
without restating the whole expression, use add, remove and separator on <attribute>:
<!-- Base view --><field name="due_date" readonly="state in ('done', 'cancelled')"/>
<!-- Inheriting view --><field name="due_date" position="attributes"> <attribute name="readonly" add="is_locked" separator="or"/></field>erp_expr::combine_python_attribute combines the texts: add appends with the separator, remove
drops a matching operand. It does not parse or check the expressions. The separator must be and or
or; a missing or other separator fails with ExprError::Modifier (SPEC-DATA-054). See
views for the other position values.
Sandboxing and security limits
Section titled “Sandboxing and security limits”Expressions are untrusted input. The evaluator has no access to the operating system, files,
environment variables or threads. Every parse-and-evaluate call gets a fresh budget
(EvalLimits, ADR 0020 §1). The values below are a ceiling: the with_* methods can only lower
them.
| Limit | Ceiling | Error message (ExprError::LimitExceeded) |
|---|---|---|
| Source length | 64 KiB | refused before parsing |
| Nesting depth (syntax tree, evaluation and produced values) | 100 | value nesting depth limit of N exceeded |
| Evaluation steps | 1,000,000 | evaluation step limit of N exceeded |
| Size of one produced value | 1 MiB | value of N bytes exceeds the per-value limit of N bytes |
| Total bytes produced by one evaluation | 16 MiB | evaluation memory budget of N bytes exceeded |
| Format width | 1,000 | refused when formatting |
Checked 64-bit arithmetic: integer arithmetic is checked. An integer outside the 64-bit range
fails with ExprError::Overflow (OverflowError: ...); division or modulo by zero fails with
ExprError::ZeroDivision (ZeroDivisionError: ...). Nothing overflows silently and nothing panics.