Tutorial
5. Declare reusable expressions
A function can take expressions and return an expression. A declaration states which columns such an expression reads, and which data type it gives.
Declare the column that an expression reads
Section titled “Declare the column that an expression reads”column("price", pl.Float64) declares an expression that reads the column price as a Float64, and gives it back:
1import polars as pl
2
3from astrolabe import Columns, TypedDataFrame, column
4
5
6class Trades(Columns):
7 symbol: pl.String
8 price: pl.Float64
9 quantity: pl.Int64
10
11
12trades: TypedDataFrame[Trades]
13Price = column("price", pl.Float64)
14
15
16def discounted(price: Price) -> Price:
17 return price * 0.9
18
19
20trades.with_columns(discounted(pl.col("price")))
21discounted(pl.col("quantity"))
↑error: Argument "price" does not match its declared type: it uses column "quantity", which the declared type does not allow [expression-fit]
22discounted(pl.col("price").sum())
↑error: Argument "price" does not match its declared type: it combines rows into one value, but the declared type works row by row [expression-fit]
- The first call passes:
pl.col("price")fits the declaration. pl.col("quantity")reads another column.pl.col("price").sum()combines the rows into one value, and the declaration works row by row.
The checker checks the declaration where you write it, and the fit of each argument at each call. See Declare expression types for expressions that read several columns, aggregations and literals.