Defaults¶
API Documentation
Default values¶
Columns missing from the source DataFrame fall back to a default. default= takes a
literal or None and builds a column of the field's annotated type, so
default=None is a typed null (string, array, struct, ...), not a void column:
import attrs
import pyspark.sql.functions as F
import typespark as ts
class T(ts.DataFrame):
surname: ts.String = ts.field(default="Doe")
nickname: ts.String = ts.field(default=None)
tags: ts.Array[ts.String] = ts.field(default=None)
For an expression, use factory= with a callable returning a typed column, or an
attrs.Factory(..., takes_self=True) to derive from other fields:
class U(ts.DataFrame):
age: ts.Int
next_age: ts.Int = ts.field(
factory=attrs.Factory(
lambda self: self.age + 1, takes_self=True
)
)
created: ts.Date = ts.field(
factory=lambda: ts.Date(F.current_date())
)
With a converter=, a default is the converter's input, as in attrs: the
literal is built as the converter's parameter type (the annotated type if that
can't be read, e.g. for a lambda), and the converter turns it into the field value.
def to_long(x: ts.Integer) -> ts.Long:
return ts.Long(x)
class V(ts.DataFrame):
# 5 is built as an Integer, then converted
total: ts.Long = ts.field(converter=to_long, default=5)
To default a struct field to a struct built from its own defaults, wrap it in a lambda:
class W(ts.DataFrame):
props: Props = ts.field(factory=lambda: Props())
Passing the class (factory=Props) fails type checking when Props has literal
defaults, because pyright checks default="..." against the column type when it
treats the class as a callable.
On a ts.decimal(precision, scale) field, a literal default is built with that
precision and scale (ts.decimal(13, 6, default=None) is a decimal(13,6) null).
Defaults are built lazily, so defining the class needs no Spark session.
default= takes a literal or None; a column expression goes in factory=
(factory=lambda: ts.Date(F.current_date())). A column as default= is a TypeError.
Struct subfield defaults¶
Defaults on a Struct's own fields apply when the struct is built (Props(...) or
factory=lambda: Props()), not when nested data is read. If a struct column in the
data lacks a subfield, from_df() raises MissingColumnError (create() with dicts
gives null); the subfield's default is not filled in. To fill a struct on read, put
the default on the DataFrame's struct field itself, as above.