Schema generation¶
API Documentation
Any model can emit its PySpark StructType. The model is the single description of the
data: the same class types your code and declares your tables.
import typespark as ts
class Address(ts.Struct):
city: ts.String
"""City name"""
class Customer(ts.DataFrame):
customer_id: ts.String
"""Customer number from the CRM"""
name: ts.String # Full name
address: Address
"""Billing address"""
schema = Customer.generate_schema()
# StructType([
# StructField("customer_id", StringType(), True,
# {"comment": "Customer number from the CRM"}),
# StructField("name", StringType(), True,
# {"comment": "Full name"}),
# StructField("address", StructType([
# StructField("city", StringType(), True,
# {"comment": "City name"}),
# ]), True, {"comment": "Billing address"}),
# ])
Everything in the schema comes from the class:
| In the model | In the StructField |
|---|---|
Attribute name, or df_alias= (see Aliases) |
name |
Column type, ts.decimal(precision, scale) (see Columns) |
data type |
nullable= (see Fields) |
nullable |
| Docstring or comment | {"comment": ...} metadata |
Struct and Array[T] fields (see Nested data) |
nested StructType / ArrayType |
Column comments¶
A field's documentation becomes its column comment. TypeSpark reads it with simple-parsing's attribute docstrings and follows its conventions:
- a docstring directly below the attribute:
"""Customer number from the CRM""", - a
#comment on the same line:name: ts.String # Full name, - a
#comment on the line above.
A docstring below the attribute wins over a comment. Multi-line docstrings keep their
line breaks. Struct fields get comments too, inside the nested StructType.
Spark uses the comment metadata as the column comment when it creates a table from the
schema, so the comments show up in your catalog:
spark.catalog.createTable(
"crm.customers", schema=Customer.generate_schema()
)
Comments need the source
Comments are read from the class's source code. A model defined where Python keeps
no source (python -c, code piped to python -, a bare REPL) generates a schema
without comments.