Why TypeSpark¶
PySpark code refers to columns by string. Nothing checks those strings until Spark runs
the query, every output column needs a hand-written .alias(), and a function that takes
and returns DataFrame says nothing about what's inside. TypeSpark puts the schema in a
class, so your editor and type checker can see it.
Classes you already know how to write¶
A model is declared like a dataclass. The difference is the scale: a dataclass instance is one record, while a model instance is a whole DataFrame, and each attribute is a column of it.
class OrderRow(ts.DataFrame):
"""One row per order."""
order_id: ts.String
"""Order number"""
amount: ts.Double
status: ts.String = ts.field(default="open")
tags: ts.Array[ts.String] = ts.field(default=None)
from dataclasses import dataclass, field
@dataclass(frozen=True)
class OrderRow:
"""One order."""
order_id: str
"""Order number"""
amount: float
status: str = "open"
tags: list[str] = field(default_factory=list)
Models are attrs classes, so what you know from attrs and dataclasses carries over:
- Field options go through
ts.field:default=,factory=(includingattrs.Factory(..., takes_self=True)),converter=,alias=. See Fields and Defaults. - Docstrings under an attribute become column comments.
- Inheritance and mixins combine columns and behaviour. See Models.
- Frozen: assigning to a column raises
FrozenInstanceError. Operations return new DataFrames. - Editor and type checker support comes from
dataclass_transform(PEP 681), the same mechanism dataclass-like libraries use, so the constructor's keywords and types are checked.
Typed functions¶
typespark.functions mirrors pyspark.sql.functions, with typed arguments and results:
tsf.sum of a Double is a Double, tsf.date_trunc takes a Timestamp and only the
units Spark knows, and returns a Timestamp. Types flow from function to function, so
the target model checks the end result.
Models
class OrderEvent(ts.DataFrame):
order_id: ts.String
amount: ts.Double
ordered_at: ts.Timestamp
class DailyRevenue(ts.DataFrame):
day: ts.Timestamp
revenue: ts.Double
def daily_revenue(events: OrderEvent) -> DailyRevenue:
return DailyRevenue(
events,
day=tsf.date_trunc("DAY", events.ordered_at).group(),
revenue=tsf.sum(events.amount), # Double
)
Wrong arguments are type errors:
tsf.date_trunc("DAYS", events.ordered_at) # type error: not a unit
tsf.upper(events.amount) # type error: amount is a Double
wrong = events.select(
F.date_trunc("DAYS", "ordered_at"), # runs: null
F.upper("amount"), # runs: the number as a string
)
Both run without an error, even with ANSI mode on. Spark returns null for the
unknown unit, and turns the number into a string. You find out from the data.
See Functions and the API Documentation for the full list.
Revenue per customer¶
Join orders to customers, group, aggregate:
import typespark as ts
import typespark.functions as tsf
class Order(ts.DataFrame):
order_id: ts.String
customer_id: ts.String
amount: ts.Double
class Customer(ts.DataFrame):
customer_id: ts.String
name: ts.String
class CustomerRevenue(ts.DataFrame):
customer_id: ts.String
name: ts.String
revenue: ts.Double
orders: ts.Long
def customer_revenue(
orders: Order, customers: Customer
) -> CustomerRevenue:
joined = orders.join(
customers,
orders.customer_id == customers.customer_id,
"left",
)
return CustomerRevenue(
joined,
customer_id=customers.customer_id.group(),
name=customers.name.group(),
revenue=tsf.round(tsf.sum(orders.amount), 2),
orders=tsf.count(orders.order_id),
)
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
from pyspark.sql import types as T
CUSTOMER_REVENUE_SCHEMA = T.StructType(
[
T.StructField("customer_id", T.StringType()),
T.StructField("name", T.StringType()),
T.StructField("revenue", T.DoubleType()),
T.StructField("orders", T.LongType()),
]
)
def customer_revenue(
orders: DataFrame, customers: DataFrame
) -> DataFrame:
o = orders.alias("o")
c = customers.alias("c")
return (
o.join(
c,
F.col("o.customer_id") == F.col("c.customer_id"),
"left",
)
.groupBy(F.col("c.customer_id"), F.col("c.name"))
.agg(
F.round(F.sum("o.amount"), 2).alias("revenue"),
F.count("o.order_id").alias("orders"),
)
)
Both produce the same rows, and CustomerRevenue.generate_schema() equals
CUSTOMER_REVENUE_SCHEMA.
| TypeSpark | PySpark | |
|---|---|---|
| Column references | Attributes: orders.amount, autocompleted |
Strings: "o.amount", F.col("c.name") |
| Output column names | Aliased automatically from the keywords | An .alias() per column, easy to forget |
| Output schema | Generated from the model: generate_schema() |
Written again by hand, free to drift |
| Function signature | Order and Customer in, CustomerRevenue out |
DataFrame in, DataFrame out |
| Same-named columns in a join | Each DataFrame's columns know their side | alias("o") + "o.customer_id" strings |
| A typo is found | In your editor | When Spark runs the query |
| Function arguments | Type checked, units included | Wrong types are cast, unknown units give null |
| Finding where a column is used | Find references, exact | Text search for a string |
| Finding where a model is used | Find references on the class | Every function says DataFrame |
| Renaming a column | Rename refactor | Search and replace strings |
Automatic aliasing¶
Every keyword passed to a model's constructor is aliased to that column's name: no
.alias() calls, and the names come from the model.
Model
class OrderSummary(ts.DataFrame):
order_id: ts.String
amount_rounded: ts.Double
is_large: ts.Bool
def summarize(orders: Order) -> OrderSummary:
return OrderSummary(
orders,
order_id=orders.order_id,
amount_rounded=tsf.round(orders.amount, 2),
is_large=orders.amount > 1000,
)
A misspelled or missing keyword is a type error.
def summarize(orders: DataFrame) -> DataFrame:
return orders.select(
"order_id",
F.round("amount", 2).alias("amount_rounded"),
(F.col("amount") > 1000).alias("is_large"),
)
Forget one .alias() and nothing complains. Spark names the column after the
expression, and the mistake shows up downstream, as a missing column or a table
with the wrong column names:
summary = orders.select(
"order_id",
F.round("amount", 2), # column: "round(amount, 2)"
F.col("amount") > 1000, # column: "(amount > 1000)"
)
A typo¶
tsf.sum(orders.amont)
Found by the type checker, before anything runs:
pyright: Cannot access attribute "amont" for class "Order"
mypy: "Order" has no attribute "amont"; maybe "amount"?
total = orders.select(F.sum("amont")) # a runtime error
Found at runtime, when Spark analyses the query: in a pipeline, only once that step is reached.
AnalysisException:
[UNRESOLVED_COLUMN.WITH_SUGGESTION] A column, variable,
or function parameter with name `amont` cannot be
resolved. Did you mean one of the following? [`amount`,
`order_id`, `customer_id`].
The same goes for a missing output column, a misspelled keyword, or a value of the wrong type: the constructor's signature comes from the model, so the type checker knows it.
Symbolic references¶
Columns are attributes and models are classes, so your editor's code navigation works on them like on any other Python code: go to definition, find all references, rename.
Model
class Refund(ts.DataFrame):
order_id: ts.String
amount: ts.Double
def large_orders(orders: Order) -> Order:
return orders.filter(orders.amount > 1000) # Order.amount
def total_refunded(refunds: Refund) -> ts.DataFrame:
# Refund.amount
return refunds.select(tsf.sum(refunds.amount))
- Find references on
Order.amountlistslarge_orders, and only that:Refund.amountis a different attribute. - Find references on
Orderlists every transform that takes or returns orders, across modules: the model's lineage through your code. - Rename
Order.amountupdates every use of it and none ofRefund's. To keep the Spark column name while renaming the attribute, usedf_alias=.
def large_orders(orders: DataFrame) -> DataFrame:
return orders.filter(F.col("amount") > 1000) # "amount"
def total_refunded(refunds: DataFrame) -> DataFrame:
return refunds.select(F.sum("amount")) # also "amount"
- Searching for
"amount"finds both functions, plus every other"amount"in the codebase, in any DataFrame, comment or log message. Nothing says which table a string belongs to. - Finding where orders are used means reading the code: every function takes and
returns
DataFrame. - Renaming the column is a search and replace over strings, hoping the matches are the right ones.
Self-joins¶
Models
class Referral(ts.DataFrame):
customer_id: ts.String
referred_by: ts.String
class ReferralName(ts.DataFrame):
customer: ts.String
referrer: ts.String
def referral_names(
referrals: Referral, customers: Customer
) -> ReferralName:
customer = customers.alias("customer")
referrer = customers.alias("referrer")
joined = referrals.join(
customer, referrals.customer_id == customer.customer_id
).join(
referrer, referrals.referred_by == referrer.customer_id
)
return ReferralName(
joined,
customer=customer.name,
referrer=referrer.name,
)
def referral_names_raw(
referrals: DataFrame, customers: DataFrame
) -> DataFrame:
r = referrals.alias("r")
customer = customers.alias("customer")
referrer = customers.alias("referrer")
joined = r.join(
customer,
F.col("r.customer_id") == F.col("customer.customer_id"),
).join(
referrer,
F.col("r.referred_by") == F.col("referrer.customer_id"),
)
return joined.select(
F.col("customer.name").alias("customer"),
F.col("referrer.name").alias("referrer"),
)
See Joins.
Nested data¶
Reading fields of an exploded array takes two steps in PySpark. In TypeSpark it's one constructor call:
Models
import typespark as ts
import typespark.functions as tsf
class Area(ts.Struct):
id: ts.String
value: ts.Double
class Building(ts.DataFrame):
building_id: ts.String
areas: ts.Array[Area]
class BuildingArea(ts.DataFrame):
building_id: ts.String
area_id: ts.String
value: ts.Double
def flatten(df: Building) -> BuildingArea:
return BuildingArea(
df,
building_id=df.building_id,
area_id=df.areas.explode(lambda a: a.id),
value=df.areas.explode(lambda a: tsf.round(a.value, 2)),
)
exploded = raw.select(
"building_id", F.explode("areas").alias("area")
)
flat = exploded.select(
"building_id",
F.col("area.id").alias("area_id"),
F.round("area.value", 2).alias("value"),
)
See Generators.
Typed layer or models?¶
TypeSpark isn't the only way to put types on PySpark. The best-known alternative,
typedspark, is a typed layer: a schema class
lists the columns, and DataSet[Order] is a PySpark DataFrame annotated with that schema.
You keep writing PySpark, and reference columns through the schema class.
TypeSpark makes the class the DataFrame itself: a model whose instances hold the data, whose columns belong to an instance, and whose expressions are typed. The same summary from Automatic aliasing, both ways:
class OrderSummary(ts.DataFrame):
order_id: ts.String
amount_rounded: ts.Double
is_large: ts.Bool
def summarize(orders: Order) -> OrderSummary:
return OrderSummary(
orders,
order_id=orders.order_id,
amount_rounded=tsf.round(orders.amount, 2),
is_large=orders.amount > 1000,
)
from pyspark.sql import functions as F
from pyspark.sql.types import BooleanType, DoubleType, StringType
from typedspark import Column, DataSet, Schema, transform_to_schema
class Order(Schema):
order_id: Column[StringType]
amount: Column[DoubleType]
class OrderSummary(Schema):
order_id: Column[StringType]
amount_rounded: Column[DoubleType]
is_large: Column[BooleanType]
def summarize(orders: DataSet[Order]) -> DataSet[OrderSummary]:
return transform_to_schema(
orders,
OrderSummary,
{
OrderSummary.amount_rounded: F.round(Order.amount, 2),
OrderSummary.is_large: Order.amount > 1000,
},
)
What the model approach adds:
- Typed expressions.
orders.amount > 1000is aBool, andis_large=orders.amountis a type error in your editor. In a typed layer, expressions are plain PySpark columns: the mistake surfaces when the result is validated at runtime. - Columns that belong to a DataFrame.
orders.amountis bound toorders, so joining two DataFrames that share column names needs no extra step (a self-join takes one.alias()). With columns on the schema class,Order.amountis just a name, and such joins need the schema registered to each DataFrame first. - Classes with behaviour. Models carry methods, inherit and mix in columns, and work with generics. See Models.
- Transforms built in. Aggregation, explode and windows are typed parts of the model's constructor and functions.
What a typed layer does well: a DataSet is a PySpark DataFrame, so every PySpark API
accepts it without unwrapping, and typedspark validates a DataFrame's columns and types
at runtime and has tooling for loading schemas from a catalog.
No runtime cost¶
TypeSpark doesn't run your data through Python. Every operation calls the PySpark operation it wraps, and Spark runs the same plan it would for the hand-written version. The typing exists for your editor and type checker. See Generators → How it runs for the one place TypeSpark shapes the query itself, and the optimized plan it ends up with.