Skip to content

Models

API Documentation

typespark.DataFrame
typespark.Struct

A model is a class whose attributes are typed columns. Subclass ts.DataFrame to describe a Spark DataFrame. An instance is a typed DataFrame: it wraps a Spark DataFrame (pyspark.sql.DataFrame) and gives you its columns as attributes.

TypeSpark adds no execution layer. A typed DataFrame holds the Spark DataFrame, every operation calls the Spark operation, and Spark runs the same plan it would for hand-written code. What the model adds is a class: a place for types, names, defaults and behaviour.

Define a model

Annotate attributes with column types. A docstring directly under an attribute becomes the column's comment in the generated schema.

import typespark as ts


class Person(ts.DataFrame):
    name: ts.String
    """Full name"""
    age: ts.Int

Wrap and unwrap

from_df() wraps a Spark DataFrame in a model, and to_spark() gives it back:

person = Person.from_df(raw_df)  # wrap: a Person DataFrame

older = person.filter(person.age > 21)  # still a Person
names = person.select(person.name)  # a plain ts.DataFrame
# unwrap: the plain pyspark DataFrame
spark_df = older.to_spark()

Operations that keep the columns return the same model: filter, where, qualify, orderBy, limit, distinct, dropDuplicates, union (with the same model), leftsemi / leftanti, alias, cache, ...

Operations that change the columns (select, withColumn, drop, join, crossJoin) return a plain ts.DataFrame, since no model describes the result. To get a typed result, build the target model.

Build a new typed DataFrame

Call a model with a source DataFrame and one keyword per column to build it from the source:

Model
class Report(ts.DataFrame):
    number: ts.Integer
    greeting: ts.String
report = Report(
    person,
    number=person.age * person.age,  # aliased to "number"
    greeting=ts.String("Hello"),  # aliased to "greeting"
)

This is how transforms are written: see Transforms.

Create from local data

create() builds a typed DataFrame straight from Python data, using the schema generated from the class, shorthand for Person.from_df(spark.createDataFrame(data, schema)):

# tuples, positional
Person.create([("Alice", 30), ("Bob", 25)])
# dicts / Rows, by column name
Person.create([{"name": "Alice", "age": 30}], spark)
Person.create(pandas_df)  # pandas DataFrame

spark defaults to the active session. Columns left out of the data get their default, computed in Spark exactly as in from_df():

  • dicts / Rows / pandas: a column counts as provided if any row has it. A row missing a key of a provided column gets null, not the default.
  • tuples: give either every column (defaults overridden) or only the columns without defaults, in declaration order.

Behaviour

A model is a regular Python class, so it can carry behaviour next to its columns: properties that return a column, methods that return a filtered DataFrame, and methods that return a condition to use in a filter or a join.

from typing import Self


class Validity(ts.DataFrame):
    valid_from: ts.Timestamp
    valid_to: ts.Timestamp

    @property
    def is_current(self) -> ts.Bool:  # (1)!
        return self.valid_to.isNull()

    def current(self) -> Self:  # (2)!
        return self.filter(self.is_current)

    def overlaps(self, other: "Validity") -> ts.Bool:  # (3)!
        return (self.valid_from < other.valid_to) & (
            other.valid_from < self.valid_to
        )
  1. A derived column. Use it like any other: df.filter(df.is_current).
  2. Self keeps the subclass type: on a subclass, current() returns the subclass.
  3. A condition between two DataFrames, for example as a join condition.

Inheritance

Subclasses inherit columns and behaviour, and a model can combine several bases. Shared column sets (validity windows, audit columns, change-feed metadata) become one class that any model can mix in:

class Customer(ts.DataFrame):
    customer_id: ts.String
    name: ts.String


class CustomerHistory(Customer, Validity):
    pass
# a column from Customer
a_names = history.filter(history.name.like("A%"))
current = a_names.current()  # a method from Validity

Column order

Columns follow attrs' order: fields from base classes come first, in reverse method resolution order. CustomerHistory above has valid_from and valid_to before customer_id and name. This matters for positional data in create().

Generic functions

A function can take any model and return the same one:

def dedupe[T: ts.DataFrame](df: T, *keys: ts.Column) -> T:
    return df.dropDuplicates(list(keys))

Lazy DataFrames

Model.lazy() gives a typed DataFrame with columns and no data: the typed analog of F.col(...). Use it to build conditions and column lists before there is a DataFrame, for example a merge condition between two aliases:

a = CustomerHistory.lazy("a")
b = CustomerHistory.lazy("b")
same = (a.customer_id == b.customer_id) & a.overlaps(b)
# Column<'((a.customer_id = b.customer_id) AND ...)'>

Any operation that needs data (to_spark(), filter, select, show, ...) raises LazyDataFrameError.

Built on attrs

Models are frozen attrs classes, declared through dataclass_transform (PEP 681) so editors and type checkers treat them like dataclasses. In practice:

  • ts.field(...) takes attrs' field options (default=, factory=, converter=, alias=, ...) next to TypeSpark's own (df_alias=, nullable=). See Fields.
  • attrs introspection works: attrs.has(Person) is True, and attrs.fields(Person) lists the columns, after two private fields that hold the Spark DataFrame and its alias.
  • Instances are frozen: assigning to a column raises FrozenInstanceError.

What TypeSpark adds on top is the Spark side: the wrapped DataFrame, typed columns, and operations that return new typed DataFrames.

Struct models

A ts.Struct subclass is a model too: it describes a struct column, a nested record inside a DataFrame. An instance is itself a typed column, wrapping a Spark struct column, with its fields as attributes. See Nested data.

Fields, aliases and behaviour work the same way as on DataFrame models.

Defaults differ

A struct's subfield defaults are not applied when reading data. See Struct subfield defaults.