Skip to content
ERPForAll DocsDevelopment

    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).


    Expressions are evaluated when data files are loaded (install and upgrade) and wherever a host evaluates an expression it stores:

    1. 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')])]"/>
    2. 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}"/>
    3. Search domains (domain="[...]"): Odoo domain lists of (field, operator, value) tuples:

      <field name="partner_id" domain="[('is_company', '=', True), ('parent_id', '=', False)]"/>
    4. View modifiers (invisible="...", readonly="...", required="..."): conditions on the record’s values in forms and lists:

      <field name="reason" invisible="state != 'rejected'" required="state == 'rejected'"/>

    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 &, |, ^, <<, >>.
    • 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.


    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’s Command namespace 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 as DateTime) is the datetime class: call it to build a value (datetime(2026, 1, 2)) or use datetime.now() and datetime.today(); it has no other attributes, so datetime.date(...) and datetime.timedelta(...) are refused. timedelta(days=1) and relativedelta(months=1) are top-level names, and time.strftime('%Y') formats the current time. now(), today() and time.strftime() need a clock; the standard context has none and refuses them with a ValueError that 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 resolve ref('module.xmlid') through its XML-id resolver (which reports a missing id) and answer record, search and group lookups. Record access through obj and env needs EvalContext::with_model. Where the host has not provided them, ref, obj, env, user, has_group and version raise a NameError that names the provider instead of returning an empty value.


    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.


    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.

    LimitCeilingError message (ExprError::LimitExceeded)
    Source length64 KiBrefused before parsing
    Nesting depth (syntax tree, evaluation and produced values)100value nesting depth limit of N exceeded
    Evaluation steps1,000,000evaluation step limit of N exceeded
    Size of one produced value1 MiBvalue of N bytes exceeds the per-value limit of N bytes
    Total bytes produced by one evaluation16 MiBevaluation memory budget of N bytes exceeded
    Format width1,000refused 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.