Jump to content

Python UDTF

From Open Lakehouse Wiki
Revision as of 00:52, 25 November 2026 by Open Lakehouse Wiki sync (talk | contribs) (Sync from open-lakehouse/wiki@7c9abaa)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Python UDTF
Also known as Python user-defined table function, @udtf
Field Distributed data processing
Introduced Apache Spark 3.5.0 (SPARK-43797)
Key parts Handler class with eval; optional __init__, analyze, terminate, cleanup; output schema; table arguments
Open source implementations Apache Spark (PySpark)
Related User-defined function (Spark), Arrow-optimized Python UDF, Python data source API (Spark)
Last verified 23 November 2026 against the v4.3.0 tag of apache/spark (the PySpark UDTF tutorial, python/pyspark/sql/functions/builtin.py, python/pyspark/sql/udtf.py, python/pyspark/sql/connect/udtf.py, examples/src/main/python/sql/udtf.py, SQLConf.scala, the PySpark migration guide) and the Spark 3.5.0 and 4.1.0 release notes.

In Apache Spark, a Python UDTF (Python user-defined table function) is a Python class, registered with PySpark, whose eval method can return zero or more rows for each call, so that the function produces a whole table instead of a single value.[1] A UDTF is called in the FROM clause of a SQL query or directly from Python, and its arguments can be scalar expressions or one input table.[1] Python UDTFs were introduced in Spark 3.5.0.[2]

What is a Python UDTF used for?

The PySpark user guide recommends a Python UDTF when a function must generate several rows and columns and benefit from Python libraries.[3] It lists these use cases:[3]

  • Exploding nested data such as arrays or structs into multiple rows.
  • Splitting strings into several rows or columns.
  • Generating rows from input ranges, such as sequences of numbers, timestamps or dates.
  • Computations that need Python libraries, such as statistical functions or machine learning inference, where a SQL table function would not be enough.

A scalar UDF returns exactly one value per input row; a UDTF can return any number of rows, each with several columns.[3]

How do you write a Python UDTF?

A Python UDTF is a class with a required eval method that yields output rows as tuples, lists or pyspark.sql.Row objects. Optional methods are __init__ (called once per UDTF instance on the executor), terminate (called after all input rows of a partition have been processed, and able to yield more rows), cleanup (always called at the end, even after an error) and a static analyze method.[1]

The output schema is a StructType or a DDL string, given in the returnType of the @udtf decorator or returned by analyze.[1] A one-column row must be yielded with a trailing comma, for example yield x,.[1]

The following PySpark example runs on Spark 4.3.0. It defines a UDTF, calls it from Python, registers it and calls it from SQL, including with a LATERAL join.

from pyspark.sql.functions import lit, udtf

@udtf(returnType="word: string")
class WordSplitter:
    def eval(self, text: str):
        for word in text.split(" "):
            yield (word.strip(),)

WordSplitter(lit("hello world")).show()

spark.udtf.register("split_words", WordSplitter)
spark.sql("SELECT * FROM split_words('hello world')").show()
spark.sql(
    "SELECT * FROM VALUES ('Hello World'), ('Apache Spark') t(text), "
    "LATERAL split_words(text)"
).show()

The example follows the UDTF examples shipped with Spark 4.3.0.[4]

How do table arguments work?

A Python UDTF can take one input table as an argument, alongside scalar arguments. In SQL the table is passed with the TABLE keyword, either as TABLE(t) or as a subquery such as TABLE(SELECT a, b FROM t). Each input row reaches eval as a Row.[1]

The call can ask Spark to partition the input table: PARTITION BY guarantees that all rows with the same values of the partitioning expressions are consumed by one instance of the UDTF class, and WITH SINGLE PARTITION sends all rows to one instance. An ORDER BY clause sets the row order within each partition.[1] For example: SELECT * FROM my_udtf(TABLE(events) PARTITION BY user_id ORDER BY ts).

The analyze method can request the same partitioning, ordering and column selection itself, through the partitionBy, withSinglePartition, orderBy and select fields of AnalyzeResult, so that callers can write just TABLE(t).[1] analyze also lets a UDTF compute its output schema from its arguments at query planning time, instead of declaring a fixed returnType.[1]

An eval method can raise SkipRestOfInputTableException to skip the remaining rows of the current partition and go straight to terminate; any other exception aborts the UDTF and fails the query.[1]

Is a Python UDTF Arrow-optimized?

Since Spark 4.2, Python UDTFs use Apache Arrow for data transfer by default: spark.sql.execution.pythonUDTF.arrow.enabled defaults to true, and setting it to false restores the earlier behaviour.[5][6] The useArrow argument of @udtf overrides the configuration for one UDTF.[7] The tutorial says Arrow helps most when each input row produces a large result table.[1] Arrow optimization for UDTFs was first added in Spark 3.5.0 (SPARK-43964).[2]

An Arrow-optimized UDTF still runs eval on Python objects. Spark 4.1.0 added a separate decorator, arrow_udtf (SPARK-52979), whose eval receives PyArrow RecordBatch or Array objects and yields PyArrow tables or record batches, for vectorized processing without row-by-row overhead.[7][8]

Limitations

  • A UDTF cannot create or reference the Spark session; trying to do so causes a serialization error.[1]
  • A UDTF call accepts at most one table argument.[1]
  • terminate may hold a whole partition in memory if the UDTF buffers rows until the end, and the tutorial warns about memory use in that pattern.[1]

PySpark 4.3.0 also ships a Python UDTF implementation for Spark Connect clients (pyspark.sql.connect.udtf).[9]

See also

References

  1. ↑ 1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 1.11 1.12 1.13 Python User-defined Table Functions (UDTFs) (PySpark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  2. ↑ 2.0 2.1 Spark Release 3.5.0. Apache Software Foundation.Retrieved 2026-11-23.
  3. ↑ 3.0 3.1 3.2 Chapter 5: Unleashing UDFs & UDTFs (PySpark 4.3.0 user guide). Apache Software Foundation.Retrieved 2026-11-23.
  4. ↑ examples/src/main/python/sql/udtf.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  5. ↑ Upgrading PySpark (PySpark 4.3.0 migration guide). Apache Software Foundation.Retrieved 2026-11-23.
  6. ↑ SQLConf.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  7. ↑ 7.0 7.1 python/pyspark/sql/functions/builtin.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
  8. ↑ Spark Release 4.1.0. Apache Software Foundation.Retrieved 2026-11-23.
  9. ↑ python/pyspark/sql/connect/udtf.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.