Expressions and functions
Daft expressions are deferred descriptions of values used by DataFrame transformations. They combine columns, literals, operators, built-in functions, aggregates, windows, and Python user functions into a typed expression tree that the native plan can resolve and evaluate. See the parent page DataFrame API and lazy workflows, with lifecycle context in Lazy DataFrame lifecycle and data context in Data model and micropartitions.
Expression model
Expression trees
An Expression represents a value to compute later rather than a value computed when Python builds the workflow. col("name") refers to a column, lit(value) supplies a constant, and operators or functions create new nodes from these inputs. DataFrame methods use the resulting tree in projections, filters, sorts, joins, aggregates, and other plan operations.
Expressions are composable. A normal Python value passed as an expression argument becomes a literal, while an existing expression remains a column- or computation-based node. This lets a transformation mix row values with fixed settings or with values from other columns without moving the work into Python row loops.
The expression tree also carries a name. A column keeps its input name, a literal uses literal, and a derived expression normally follows its first input. Use alias() when the output name is part of the downstream contract.
References: daft/…/expressions.py• L42-170 daft/…/expressions.py• L236-345 src/…/mod.rs• L218-307 src/…/mod.rs• L2304-2373
Expression resolution
Resolution connects symbolic column names to the schema of the current plan. The DataFrame and SQL front ends can create unresolved references. The logical plan builder checks their scope, expands supported wildcards, resolves nested access, and rejects missing or ambiguous columns before execution.
After logical resolution, native planning can bind references to fields in a schema. A bound expression has no unbound column references and can be passed to record-batch or micropartition evaluation. This boundary keeps name lookup in planning instead of repeating it during row computation.
Resolution depends on the current workflow position. A projection, rename, or join can change the names and scopes that a later expression may use. See Lazy DataFrame lifecycle for how this fits into plan construction.
References: src/…/resolve_expr.rs• L20-126 src/…/resolve_expr.rs• L128-175 src/…/resolve_expr.rs• L236-255 src/…/bound_expr.rs• L14-89
Expression projections
An ExpressionsProjection is an ordered set of output expressions used to form a table result. It requires every expression to have a unique output name, so a projection cannot silently replace one result with another.
The projection can resolve its output schema before values are evaluated. It can also identify no-op column mappings, which helps the plan recognize when an output is only a renamed or forwarded input. A projection with a wildcard may expand into several expressions during logical resolution.
References: daft/…/expressions.py• L3136-3302 src/…/mod.rs• L1307-1324 tests/…/test_expressions_projection.py• L11-183
Built-in function families
Scalar functions
Scalar functions produce one output value for each input row. The Python function modules expose the user-facing names, while the native function registry supplies the expression node and its evaluation rules. Most functions accept both expressions and ordinary Python values for their arguments.
The main scalar families are:
| Family | Purpose | Typical capabilities |
|---|---|---|
| Numeric | Transform numeric values | Arithmetic helpers, rounding, roots, trigonometry, logarithms, powers, division checks, and numeric validity checks |
| Comparison and null | Build row predicates and fill missing values | Comparisons, membership, range checks, null-safe equality, null tests, coalescing, and null filling |
| String and JSON | Inspect and transform text | Case changes, trimming, slicing, part extraction, pattern checks, regular expressions, JSON parsing, formatting, serialization, and tokenization |
| Date and time | Read or change temporal values | Date-part extraction, parsing, formatting, time-zone changes, date arithmetic, and duration conversion |
| Binary and encoding | Transform byte or encoded values | Encoding, decoding, compression, decompression, and safe variants |
| Nested data | Work with lists, maps, and structs | Element access, list construction, flattening, sorting, mapping, filtering, appending, and field unnesting |
| Similarity and domain data | Compute values for richer data | Distance and similarity measures, files, images, audio, video, URLs, tensors, embeddings, and model-based row judgments |
| Row generation | Create values without a direct input | UUIDs, random integers, monotonic IDs, and partition-key helpers |
The public Expression methods and the top-level daft.functions names are two ways to reach the same expression system. Method calls are useful for chaining from a column. Top-level functions are useful when an operation has several peer inputs or when its purpose is clearer as a named operation. The fluent surface includes operations for string parts, file and media access, and HDF5 metadata as well as common scalar transforms.
The Jev family extends scalar expressions with plain-English row predicates, classification, and scoring. jev_prob returns a probability for a condition. jev turns that probability into a Boolean threshold test. jev_choice selects one of up to 255 options, while jev_score returns a probability-weighted index across two to ten ordered levels. Each function accepts an expression as its row input, so to_struct(...) can present several fields to the model as one row value.
These functions remain deferred expressions, but their values come from the TypeSafe Jev service during execution. The service processes up to 25 rows per request, preserves null rows as null outputs, and uses a configurable model, API endpoint, key, and request timeout. The optional typesafe-sdk dependency and API key are required when a Jev expression runs.
References: daft/…/__init__.py• L3-36 daft/…/__init__.py• L99-124 daft/…/__init__.py• L162-184 daft/…/__init__.py• L185-248 daft/…/__init__.py• L249-324 daft/…/jev_.py• L1-18 daft/…/jev_.py• L26-69 daft/…/jev_.py• L71-115 daft/…/jev_.py• L122-184 daft/…/jev_.py• L187-262 daft/…/expressions.py• L1574-1707 daft/…/expressions.py• L2640-2721 daft/…/expressions.py• L2968-3086
Aggregate functions
Aggregate functions reduce many input rows into a summary value. They are used by global aggregation, grouped aggregation, and window expressions. Their result type can differ from the input type; for example, counts return an unsigned integer and means return a numeric supertype.
The aggregate family covers counts, distinct counts, sums, products, means, percentiles, medians, variance, standard deviation, extrema, Boolean reductions, arbitrary values, skew, list collection, and string concatenation. Null treatment is part of each aggregate's contract. Count supports all, valid, or null values, while many numeric summaries ignore null inputs.
An aggregate expression is not valid in every DataFrame operation. The plan resolver permits it in aggregate, pivot, window, and supported global-aggregate contexts. In grouped aggregation, non-aggregate branches must be literals, group keys, or valid aggregate expressions.
References: daft/…/agg.py• L11-43 daft/…/agg.py• L45-205 daft/…/agg.py• L208-326 src/…/resolve_expr.rs• L471-527 src/…/mod.rs• L885-1095
List and nested functions
Nested functions preserve the row as the outer unit while operating inside list, map, or struct values. Access functions return a child value. List functions can summarize or reshape each list, and struct functions can expose fields as output columns.
List mapping and filtering use element() as the reference to the current list item. This makes the inner rule an expression too, so it can use the same comparison and built-in function families as an ordinary column rule. explode() is different: it changes row count by making one row per list item and is therefore treated as a projection-level row-shaping operation.
References: daft/…/list.py• L11-102 daft/…/list.py• L105-190 daft/…/list.py• L231-379 daft/…/list.py• L382-475 daft/…/misc.py• L657-775 src/…/resolve_expr.rs• L177-234
Window functions
Window functions compute a value for each row while looking at a related set of rows. over(window) supplies the partition, order, and frame that define that related set. Ranking, offsets, first and last values, and ordinary aggregates can use this form.
The window expression is incomplete until it has a window specification. The resolver separately resolves the partition and order expressions, then the plan evaluates the completed window operation without reducing the input rows.
References: daft/…/window.py• L14-57 daft/…/window.py• L152-197 daft/…/window.py• L200-307 src/…/mod.rs• L248-257 src/…/resolve_expr.rs• L443-468
Conditional functions
Conditional expressions select a value from ordered cases. when(condition, then) starts a SQL-style CASE WHEN chain, additional when() calls add cases, and otherwise() supplies the fallback. If no case matches and no fallback exists, the result is null.
The condition must be Boolean. The result branches must be compatible with a common type, so a conditional expression can combine values such as an integer column and integer literals but cannot silently combine unrelated types.
References: daft/…/misc.py• L904-1039 daft/…/expressions.py• L3089-3133 src/…/mod.rs• L2242-2269
Type-aware behavior
Type inference
Expression typing uses the input schema and the declared types of literals and function arguments. Each expression can produce a field with a name and data type before evaluation. Arithmetic, comparison, logical, membership, conditional, null-fill, and collection operations use type rules to select a result type or report an error.
Type inference is visible to DataFrame schema inspection and to execution. It handles scalar and nested types as well as temporal units and logical types. A literal can infer types from Python values such as integers, strings, dates, timestamps, durations, lists, and nulls.
References: src/…/mod.rs• L2085-2172 src/…/mod.rs• L2173-2300 daft/…/expressions.py• L42-71 tests/…/test_expressions.py• L18-52
Casts and common types
cast() requests a conversion to a target Daft data type. try_cast() uses the same target but returns null for values that cannot convert. The target can be a Daft DataType, a supported Python type, or a supported SQL type name. Expression as_* helpers are shorthand for common casts.
Operations with more than one possible value type seek a common supertype. This applies to arithmetic inputs, fill_null, coalesce, conditional branches, and collection construction. If no safe common type exists, schema resolution fails before the operation runs.
References: daft/…/misc.py• L140-240 daft/…/expressions.py• L455-565 daft/…/expressions.py• L3253-3274 src/…/mod.rs• L2124-2132 src/…/mod.rs• L2242-2269
Null behavior
Null is a data value that represents missing input. Expressions carry null behavior through their operation rules rather than treating null as a separate table shape. Predicates such as is_null and not_null test it directly. Regular equality and Boolean operations follow the expression engine's null rules, while eq_null_safe treats two nulls as equal.
Functions can propagate, ignore, replace, or turn failures into nulls. For example, coalesce chooses the first non-null input, fill_null supplies a replacement, and safe conversion functions return null when a row cannot be converted. These differences matter when a predicate or aggregate consumes the result.
References: daft/…/misc.py• L124-138 daft/…/misc.py• L243-337 daft/…/misc.py• L620-655 daft/…/numeric.py• L309-385 src/…/mod.rs• L2111-2132
Evaluation and integration
Native evaluation
The native expression tree is the shared representation between planning and execution. Once expressions are resolved and typed, record batches evaluate them over aligned Series, and micropartitions evaluate the same expressions across their batches while producing a new schema and result partition.
This separation lets the logical plan optimize and place expression work before execution. Statistics can also be evaluated alongside partition values when the partition carries them. See Data model and micropartitions for the row and partition units used at this stage.
References: src/…/eval_expressions.rs• L11-41 src/…/eval_expressions.rs• L43-91 src/…/eval_expressions.rs• L93-134 daft/…/micropartition.py• L193-313
Python and native bridge
The Python Expression is a wrapper around the native PyExpr. Python constructors and methods build native expression nodes, and DataFrame plan methods pass those nodes into the native logical plan builder. Native results are wrapped back into Python objects for schema inspection and result access.
The bridge also exposes expression structure to Python integrations. Expressions can report whether they are columns or literals, return literal values when appropriate, serialize with the surrounding plan, and accept visitors. This keeps the public Python API small while allowing the native planner and executor to own expression meaning.
References: daft/…/expressions.py• L133-175 daft/…/expressions.py• L410-420 src/…/python.rs• L421-470 src/…/python.rs• L694-714 src/…/mod.rs• L1257-1324
Python visitors and Arrow expressions
An ExpressionVisitor walks the expression tree and lets a consumer define how each expression kind should be represented. The PyArrow visitor uses this contract to translate compatible Daft expressions into pyarrow.compute.Expression values for integrations with systems that use Arrow compute expressions.
The translation is not a complete second execution engine. It maps supported operators and functions to Arrow compute names, handles special forms such as between and coalesce, and rejects forms that Arrow cannot represent. Some arguments must be literals because Arrow's expression API requires a value at translation time.
References: daft/…/visitor.py• L14-100 daft/…/visitor.py• L103-194 daft/…/pyarrow_visitor.py• L13-49 daft/…/pyarrow_visitor.py• L50-149 daft/…/pyarrow_visitor.py• L151-199
Python user-defined functions
Python user-defined functions extend the expression system when built-ins do not cover the needed row or batch rule. A decorated function called with one or more expressions returns a deferred expression. The function runs later with values from those input expressions, while ordinary scalar calls can still run immediately as Python code.
Row-wise functions receive one value per row. Batch functions receive Series-like batches and can use vectorized Python, Arrow, or NumPy work. A function can return one value per input row, produce multiple rows as a generator, or return a struct that can be unnested into columns. The declared or inferred return type is part of the expression schema contract.
Expression.apply is a convenience form for a function on one column. It records the return type and uses a batch UDF path so the expression remains usable in aggregate contexts.
Class-backed functions defer class initialization until query execution so expensive state can be reused by function calls. Resource needs, retries, process choice, concurrency, and error policy affect execution placement rather than changing the expression's input and output meaning.
References: daft/…/__init__.py• L22-80 daft/…/__init__.py• L252-278 daft/…/__init__.py• L396-418 daft/…/udf_v2.py• L51-128 daft/…/expressions.py• L1174-1221 src/…/python.rs• L192-230 src/…/mod.rs• L339-391
Change checklist
When these files or sections are changed, remember to consider these:
- When adding or renaming a built-in function, keep the Python function name, public export, native registry name, type rule, and expression display name aligned.
- When changing an expression node, update schema inference, logical resolution, native batch evaluation, serialization, visitors, and any SQL or Arrow translation that accepts the node.
- When changing a function's accepted input types or null rules, check both scalar evaluation and the
to_fieldresult used before execution. - When changing list mapping or filtering, keep
element()replacement aligned with list evaluation and with the rule that prevents unexpected outer column references. - When changing a UDF return type or row shape, keep decorator metadata, native Python expression conversion, projection unnesting, and execution result schema aligned.
- When changing a window or aggregate expression, check the contexts in which the resolver permits it and the schema rules for grouped or windowed output.
- When changing Arrow expression support, keep the visitor's function-name overrides and literal-only argument rules aligned with the installed PyArrow API.
- When adding an
Expressionmethod for a domain function, keep its argument coercion and public method behavior aligned with the top-level function and native registry entry. - When changing a Jev function, keep its public export, optional dependency check, row serialization, batch limits, null preservation, service settings, and declared result type aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A column name is missing or ambiguous in the current plan scope | Expression resolution fails before execution | Inspect the current schema and qualify or rename inputs before building the expression |
Python and, or, or not is used with an expression | Python raises before a Daft expression is built | Use &, ` |
| A projection contains duplicate output names | The projection is rejected instead of silently choosing one result | Use alias() and keep output names unique |
| An operator or function receives incompatible types | Schema inference raises a type error | Cast inputs or choose a function that supports the input data type |
| Conditional branches, null-fill values, or coalesce inputs have no common type | The result schema cannot be formed | Convert the branches or inputs to a compatible type |
| An aggregate is used in a non-aggregate context | Plan validation rejects the expression | Use agg, groupby().agg, a supported global aggregate, or a window |
explode is used where row-shape changes are not allowed | Plan validation rejects the operation or multiple exploded lengths fail | Use it in an allowed projection and keep simultaneous exploded lengths aligned |
| A Python UDF has no reliable return type or returns an unexpected shape | Schema creation or execution fails, or output columns do not match the plan | Declare return_dtype when inference is not enough and match the declared row shape |
| A Daft expression uses a function or argument unsupported by PyArrow | to_arrow_expr() raises instead of producing an Arrow expression | Use only the supported Arrow subset or keep the expression in native Daft execution |
| Jev is used without the optional SDK or an API key | Expression construction or execution fails before a model result is returned | Install daft[jev] and pass a key or set the configured TypeSafe API key |
| A Jev choice or score list has an invalid size | The function rejects the expression before execution | Pass one to 255 distinct choices or two to ten ordered score levels |
| The Jev service returns an incomplete answer set | Batch evaluation raises instead of silently misaligning rows | Keep the service contract intact and inspect the model response when requests fail |
Key files
| File | Why to read it |
|---|---|
| daft/…/expressions.py | Defines the Python expression surface, constructors, operators, methods, conditional chains, projections, and domain-specific expression accessors. |
| daft/…/__init__.py | Shows the public groups of built-in functions exposed to DataFrame users, including the Jev family. |
| daft/…/jev_.py | Defines plain-English predicates, classification, and scoring as deferred model-backed expressions. |
| daft/…/misc.py | Illustrates casts, null handling, nested access, coalescing, and conditional expressions. |
| daft/…/list.py | Illustrates list-local expressions, element references, filters, maps, and row-changing explode behavior. |
| daft/…/agg.py | Defines the aggregate expression surface and aggregate result contracts. |
| daft/…/window.py | Defines window expression construction and attachment to window specifications. |
| src/…/mod.rs | Defines the native expression forms and the type and name rules for their results. |
| src/…/bound_expr.rs | Defines the boundary from schema-visible column references to executable bound expressions. |
| src/…/resolve_expr.rs | Shows expression scope resolution, wildcard expansion, context checks, and aggregate validation. |
| src/…/eval_expressions.rs | Shows how typed expressions produce new micropartitions during evaluation. |
| daft/…/visitor.py | Defines the visitor contract used to inspect or translate expression trees. |
| daft/…/pyarrow_visitor.py | Defines the supported Python-to-PyArrow expression translation. |
| daft/…/__init__.py | Defines the public Python UDF decorators and the expression-vs-immediate-call behavior. |
| daft/…/udf_v2.py | Defines UDF metadata such as return type, row or batch mode, and execution shape. |
| src/…/python.rs | Defines the native PyExpr binding used to carry expressions across the Python boundary. |