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.functionsmirrorspyspark.sql.functionswith typed arguments and results:tsf.upperon a number, or a misspelled unit intsf.date_trunc, is a type error instead of a silent cast ornull. - Columns are symbols, not strings. Go to definition, find references and rename work
on
people.agelike 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, andadultsreturns a typedAdult, not a bareDataFrame. - One schema. The class types your code and generates the
StructTypefor 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¶
- Why TypeSpark: the same jobs side by side with plain PySpark.
- Models and Columns: the two building blocks.
- Transforms: writing typed functions from model to model.
- Migrating from 1.x: every breaking change in 2.0.