Skip to content

TypeSpark

Bringing classes to PySpark DataFrames, built on attrs.

Declare a DataFrame like a dataclass: each attribute is a typed column. Wrap a Spark DataFrame in the class and you get autocomplete, checked column access and transforms your type checker can verify, with no .alias() boilerplate. Every operation calls PySpark directly, so Spark runs exactly the code you'd have written.

import typespark as ts
import typespark.functions as tsf


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


class Adult(ts.DataFrame):
    full_name: ts.String
    can_vote: ts.Bool


def adults(people: Person) -> Adult:
    return Adult(
        people,
        full_name=tsf.initcap(people.name),  # a typed String
        can_vote=people.age >= 18,  # aliased to "can_vote"
    )
  • Familiar syntax. If you've written a dataclass or an attrs class, you can write a model: annotations, defaults, field(...), inheritance.
  • Typed functions. typespark.functions mirrors pyspark.sql.functions with typed arguments and results: tsf.upper on a number, or a misspelled unit in tsf.date_trunc, is a type error instead of a silent cast or null.
  • Columns are symbols, not strings. Go to definition, find references and rename work on people.age like on any Python attribute.
  • Mistakes show up in your editor. A misspelled column, a missing output column or a wrong type is a type error, not a failure when Spark runs.
  • No .alias(). Each keyword is aliased to its column name, and adults returns a typed Adult, not a bare DataFrame.
  • One schema. The class types your code and generates the StructType for your tables.

Installation

pip install "typespark[pyspark]"   # with PySpark
pip install typespark              # PySpark already provided by your environment

Python 3.12+, PySpark 3.5 to 4.3. Type checking with pyright (Pylance) or mypy.

TypeSpark 2.0 is in pre-release: add --pre to install it. Without it, pip installs 1.x.

More on extras and supported versions: Installation.

Where next