Polars provides a lot of build-in expressions for you to manipulate your data and DataFrames. However, sometimes our operations on DataFrames are unique and the build-in expressions does not fit the bill. You can apply a Python function to the Polars DataFrames to do that but since it is not optimised, it is slow.
In order to create user defined functions that can be compiled and registered as an expression into the Polars library, expression plugins are required. By using expression plugins, the Polars engine will dynamically link your function at runtime and your expression will run almost as fast as native expressions. Which has the benifit of:
- Optimization
- Parallelism
- Rust native performance
But there is a catch, expression plugins are available only in Rust (because of the native functionalities mentioned above) and you will need to create your function in Rust.
The Polars user guide introduces this in its Expression plugins chapter. This workshop covers the same ground in more depth, so it is worth keeping the Polars user guide open alongside.
In this workshop, we expect you to have knowledge of Python and Polars and have a bit of Rust experience (or be able to pick it up relatively quickly). Not all concepts in Rust will be explained but we will link to material where you can find explanations.
Here are the things that you should have installed when you started this workshop:
- Install/ Update Rust(we are using rustc version 1.86.0 here)
- Make sure having Python 3.11 or above (assuming 3.13 in this workshop)
- Make sure using virtual environment (recommend using uv >= 0.4.25)
In this workshop we recommend using Unix OS (Mac or Linux). If you use Windows, you may encounter problems with Rust and Maturin. To minimise issues that you may encounter, please go through the extra checklist below:
To wirte a Polars plugin, you will have to develop in Rust. If you are not familiar with Rust, we highly recommend you first check out some of the Rust learning resources so you can be prepare for the workshop. Here are some of our recommendations:
Another tool that we will be using will be PyO3 and Maturin. To learn more about them, please check out the following:
- create a new working directory
mkdir polars-plugin-101
cd polars-plugin-101
- Set up virtual environment and activate it
uv venv .venv
source .venv/bin/activate
python -m ensurepip --default-pip
Note: the last command is needed as maturin develop cannot find pip otherwise
- Install polars and maturin
See the user guide's installation page for the other ways to install Polars.
uv pip install polars maturin
These are the versions that we are using here:
- maturin==1.15.0
- polars==1.27.1
Let's start by building a simple (but useful) expression. Imagine you would like to capitalise a series of names. In Python we have the build-in function to do so, but it is slow. We will try cresting something in Rust to do it.
Please note that this only work for ASCII characters, details please check this discussion
Use maturin to create a project:
maturin init
After that, a few files will be generated for you. However, we need to customize them for a bit. In Cargo.toml, we would like to add a bunch of dependencies:
polars = { version = "0.55" }
pyo3 = { version = "0.29", features = ["extension-module", "abi3-py311"] }
pyo3-polars = { version = "0.28", features = ["derive"] }
serde = { version = "1.0", features = ["derive"] }
After that, we will also need to include polars as our build requirements in pyproject.toml:
requires = ["maturin>=1.15,<2.0", "polars>=1.3.0"]
One more thing need to be added to the pyproject.toml, we need to make sure that the result module is named correctly so that polars can use it, add the following setting:
[tool.maturin]
module-name = "polars_plugin_101._internal"
to the tool.maturin session. We name our module _internal as it is an internal module to be used by polars.
Everything in this step — plus the scaffolding parts of steps 2 and 3 — is boilerplate you only ever type once. If you would rather skip it, there is a cargo-generate template at Cheukting/polars_plugin_template that produces exactly the same project, already configured.
Install cargo-generate once:
cargo install cargo-generate
Then generate the project:
cargo generate --git https://github.com/Cheukting/polars_plugin_template.git --name polars-plugin-101
cd polars-plugin-101
cargo generate gh:Cheukting/polars_plugin_template is the same thing spelled shorter. --name sets both the Cargo package name and the Python package directory — polars-plugin-101 gives you a polars_plugin_101/ folder, because cargo-generate also exposes the name snake_cased as crate_name. Leave --name off and it will prompt you for it.
You still need the virtual environment from Setting up; the template only covers the project files. And do read on through steps 2 and 3 regardless — the template leaves src/expressions.rs and polars_plugin_101/__init__.py as empty shells, and the rest of this workshop is about filling them in.
Next, we will start developing our expression. In src/ we have lib.rs, but we will create another file called expressions.rs to store all our custom functions.
In src/expressions.rs:
use polars::prelude::*;
use pyo3_polars::derive::polars_expr;
use std::fmt::Write;
fn capitalize_str(value: &str, output: &mut String) {
if let Some(mut first_char) = value.chars().next() {
first_char.make_ascii_uppercase();
write!(output, "{first_char}{}", &value[1..]).unwrap();
}
}
#[polars_expr(output_type=String)]
fn capitalize(inputs: &[Series]) -> PolarsResult<Series> {
let ca = inputs[0].str()?;
let out: StringChunked = ca.apply_into_string_amortized(capitalize_str);
Ok(out.into_series())
}This is a typical structure of creating a custom polars expression, the same shape as the user guide's Writing the expression example. First we will have a polars_expr that take a Series as input and gives a PolarResults. With the apply_into_string_amortized provided by polars we can processes each rows one by one without creating new String outputs.
apply_into_string_amortized will be calling our custom function capitalize_str which make a mutable borrow of the first character and make it uppercase if it is an ASCII character. If an expression takes more than one column and still outputs strings, polars::prelude::arity offers binary_elementwise_into_string_amortized which amortises the allocation the same way — we will reach for it in one of the exercises later.
After creating our custom polars_expr, we can now move back to lib.rs to wrap up the module.
In src/lib.rs:
mod expressions;
use pyo3_polars::PolarsAllocator;
/// Polars plugin expressions implemented in Rust.
#[pyo3::pymodule]
mod _internal {
use pyo3::prelude::*;
#[pymodule_init]
fn init(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add("__version__", env!("CARGO_PKG_VERSION"))
}
}
#[global_allocator]
static ALLOC: PolarsAllocator = PolarsAllocator::new();Here we use a declarative module: #[pymodule] on a mod rather than on a function, which is the style the PyO3 user guide uses. The doc comment on the module becomes the module docstring, and #[pymodule_init] lets us run arbitrary code at import time — here to add a __version__ attribute.
For details of how to create a Python module using PyO3, please check out the other workshop PyO3 101. The difference here is that we never add our expressions to the module by hand: #[polars_expr] exports each one as a C function in the compiled library, and Polars looks them up by name when we register them on the Python side in the next step. That is also why the module body only needs __version__.
The #[global_allocator] line is a separate concern: PolarsAllocator relays allocations to the allocator Polars itself uses, rather than our plugin keeping a second one of its own (it falls back to the system allocator if Polars' one is not available).
To make sure Polars can find our plugin, we need to do something on the Python side. First, we will create a __init__.py file in the folder that matches the name of your plugin module. In our case it is polars_plugin_101, remember in the pyproject.toml we have:
[tool.maturin]
module-name = "polars_plugin_101._internal"
So the name before ._internal should also matches.
Before the __init__.py itself, we need one small helper. Our functions take "something that can become a column" — an expression, a Series, or a column name as a string — and Polars has a type alias for exactly that, IntoExprColumn. But it lives in polars._typing, a private module: the leading underscore means Polars makes no promise about it, and it has already moved once (it was polars.type_aliases before Polars 1.0). So instead of importing from it, we spell out the aliases ourselves.
Create polars_plugin_101/typing.py:
"""Type aliases for the public API of this plugin.
Polars keeps these aliases in the private ``polars._typing`` module, so we
define our own here rather than importing from it.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, TypeAlias, Union
if TYPE_CHECKING:
from datetime import date, datetime, time, timedelta
from decimal import Decimal
import polars as pl
IntoExprColumn: TypeAlias = Union[pl.Expr, pl.Series, str]
PythonLiteral: TypeAlias = Union[
int, float, str, bool, bytes, date, time, datetime, timedelta, Decimal, list[Any]
]
IntoExpr: TypeAlias = Union[PythonLiteral, IntoExprColumn, None]Everything sits under if TYPE_CHECKING: so it costs nothing at runtime — only type checkers ever read it. Naming the file typing.py inside our package is safe: Python 3 uses absolute imports, so from typing import ... elsewhere still finds the standard library one. (This is the approach the cookiecutter-polars-plugins template takes, which is worth a look if you want a ready-made project skeleton.)
Next, in the polars_plugin_101/__init__.py we have:
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import polars as pl
from polars.plugins import register_plugin_function
from polars_plugin_101._internal import __version__ as __version__
if TYPE_CHECKING:
from polars_plugin_101.typing import IntoExpr, IntoExprColumn
PLUGIN_PATH = Path(__file__).parent
def capitalize(expr: IntoExpr) -> pl.Expr:
"""Capitalize String."""
return register_plugin_function(
plugin_path=PLUGIN_PATH,
function_name="capitalize",
args=expr,
is_elementwise=True,
)The from __future__ import annotations line at the top is what makes the deferred import work: annotations are kept as strings rather than evaluated, so IntoExpr never needs to exist at runtime.
The __version__ line is where the #[pymodule_init] block from our lib.rs finally pays off. Back in Step 2 we added __version__ to the compiled _internal module; this pulls it up to the top level so our users can read polars_plugin_101.__version__. The odd-looking as __version__ is not a typo — importing a name as itself is how you tell type checkers that a name is a deliberate re-export rather than an implementation detail that leaked in.
Type checkers cannot see inside a compiled extension module, though, so they have no idea _internal has a __version__ at all. We fix that with a stub file. Create polars_plugin_101/_internal.pyi containing one line:
__version__: strA .pyi file describes the types of a module without providing its implementation — exactly what we need for a module whose implementation is a .so built by Rust. As we add more to the _internal module later, this is the file that tells Python tooling what is in there.
This is using the plugin path, where our module created in Rust will be, to create a Polars expression. Feel free to customise the docstings, function name etc. All the arguments are documented under register_plugin_function in the Polars API reference.
Finally, we can build and test our plugin. Again, we will use maturin:
maturin develop
It may take a while building for the first time, so please be patient. While waiting, why not wirte a simple Python script to test this plugin expression out?
import polars as pl
from polars_plugin_101 import capitalize
df = pl.DataFrame(
{
"attendees": ["john", "mary", "connor", "sally"],
}
)
out = df.with_columns(names=capitalize("attendees"))
print(out)Congratulations, you have just created your first Polars plugin in Rust. Feel free to play around and test it out more.
For the last exercise, we have created a expression that works on strings and create strings. Let's move one step further and create an expression that work on numerical values.
Remember the formula to convert temperature in Celcius to Farenheit as:
deg_f = (deg_c * 9/5) + 32
Can we make a Polars plugin to convert a column of temperature in Celcius to Farenheit?
First, we will define the expression in src/expressions.rs:
#[polars_expr(output_type=Float64)]
fn to_farenheit(inputs: &[Series]) -> PolarsResult<Series> {
let s = &inputs[0];
let ca: &Float64Chunked = s.f64()?;
let out: Float64Chunked = ca.apply_values(|deg_c| deg_c * 9.0 / 5.0 + 32.0);
Ok(out.into_series())
}Note that this time the output_type is Float64 instead.
Next, we will have to register this expression with Polars, in polars_plugin_101/__init__.py:
def to_farenheit(expr: IntoExpr) -> pl.Expr:
"""Converting Celcius to Farenheit."""
return register_plugin_function(
plugin_path=PLUGIN_PATH,
function_name="to_farenheit",
args=expr,
is_elementwise=True,
)This is similar to what we have done in the previous example.
Now, let's test it out by maturin develop and writing some Python code. Note that the correct datatype is required for the expression to work.
Now, let's consider taking two values as inputs, they are from the same row but on a different columns. How do we go about to do that?
For example, we would like to output the larger values of the values of the two columns. In src/expressions.rs
use polars::prelude::arity::broadcast_binary_elementwise_values;
#[polars_expr(output_type=Int64)]
fn larger(inputs: &[Series]) -> PolarsResult<Series> {
let first: &Int64Chunked = inputs[0].i64()?;
let second: &Int64Chunked = inputs[1].i64()?;
let out: Int64Chunked =
broadcast_binary_elementwise_values(first, second, |first: i64, second: i64| {
std::cmp::max(first, second)
});
Ok(out.into_series())
}Here we use broadcast_binary_elementwise_values provided in polars::prelude::arity, so make sure to include the use line.
When we register it with Polars in polars_plugin_101/__init__.py:
def larger(expr1: IntoExpr, expr2: IntoExpr) -> pl.Expr:
"""Return larger value."""
return register_plugin_function(
plugin_path=PLUGIN_PATH,
function_name="larger",
args=[expr1, expr2],
is_elementwise=True,
)We take two arguments expr1 and expr2 and combine the into a list to pass in args to match the type &[Series] in our Rust input.
Now it's time to maturin develop and test it out! If you want an extra challenge, could you create an expression largest which take an arbitrary amount of inputs and always output the largest? (see possible solution here)
In the previous exercise, it assumes the data type is Int64 and if it is another numerical data type, e.g. Float64 it will not work and an error message will appear. You may wonder how to make a generic expression that return the larger numerical value, despite the data type (as long as it is numeric)?
Well, it will require some mapping work that need to be done while creating the expression. First, we will need to be able to return the result in the same type as the input. To do that, we will modify the marco here:
#[polars_expr(output_type=Int64)]
fn larger(inputs: &[Series]) -> PolarsResult<Series> {
...
}to something like:
fn same_output_type(input_fields: &[Field]) -> PolarsResult<Field> {
let field = &input_fields[0];
Ok(field.clone())
}
#[polars_expr(output_type_func=same_output_type)]
fn larger(inputs: &[Series]) -> PolarsResult<Series> {
...
}The output_type_func argument let us define the output type with a function, as the user guide describes (also covered in the pyo3-polars README).
In our code, we assume that everything is in i64, now, we have to do a check on the dtype of the series and perform the corresponding code:
#[polars_expr(output_type_func=same_output_type)]
fn larger(inputs: &[Series]) -> PolarsResult<Series> {
match inputs[0].dtype() {
DataType::Int32 => {
let result: Int32Chunked = broadcast_binary_elementwise_values(
inputs[0].i32()?,
inputs[1].i32()?,
|first: i32, second: i32| std::cmp::max(first, second),
);
Ok(result.into_series())
}
DataType::Int64 => {
let result: Int64Chunked = broadcast_binary_elementwise_values(
inputs[0].i64()?,
inputs[1].i64()?,
|first: i64, second: i64| std::cmp::max(first, second),
);
Ok(result.into_series())
}
DataType::Float32 => {
let result: Float32Chunked = broadcast_binary_elementwise_values(
inputs[0].f32()?,
inputs[1].f32()?,
|first: f32, second: f32| f32::max(first, second),
);
Ok(result.into_series())
}
DataType::Float64 => {
let result: Float64Chunked = broadcast_binary_elementwise_values(
inputs[0].f64()?,
inputs[1].f64()?,
|first: f64, second: f64| f64::max(first, second),
);
Ok(result.into_series())
}
dtype => {
polars_bail!(InvalidOperation: "dtype {dtype} not \
supported, expected Int32, Int64, Float32 or Float64.")
}
}
}Note that for f64 and f32 there are different implementation for returning the max value. The user guide's full data types table lists every DataType you may want to match on.
There is no need to change the __init__.py so we can maturin develop and test it out directly. As for extra challenge, you can also update your largest method in similar fashion.
So far we have only doing row-wise operations, what if an operation like accumulative sum or rolling average? Here we will try to perform something similar to an accumulative sum but with a twist. We will be linking up all the strings in the same column into a mega string.
In exprssions.rs, we deine the function:
#[polars_expr(output_type=String)]
fn cum_str(inputs: &[Series]) -> PolarsResult<Series> {
let s = &inputs[0];
let ca = s.str()?;
let out: StringChunked = ca
.iter()
.scan(
String::new(),
|sentence: &mut String, x: Option<&str>| match x {
Some(x) => {
sentence.push(' ');
sentence.push_str(x);
Some(Some(sentence.clone()))
}
None => Some(None),
},
)
.collect();
Ok(out.into_series())
}Note that this time we process the data as an iterator and uses the scan method which holds an internal state, which we can used to store the accumulated sentence so far.
Also note that we need to return Some(Some(sentence.clone())) instead of Some(Some(sentence)) to ensure the life time of the return values are long enough.
Next, in __init__.py:
def cum_str(expr: IntoExprColumn) -> pl.Expr:
return register_plugin_function(
plugin_path=PLUGIN_PATH,
function_name="cum_str",
args=[expr],
is_elementwise=False,
)Note that we have set is_elementwise to False and the args takes [expr] as we are expecting the whole column will be used as input.
Build and try out the cum_str expression. For an extra challenge, could you create an expression that takes multiple columns as input? You can start by extend our cum_str to string multiple columns. To join the columns, use binary_elementwise_into_string_amortized rather than a format! inside the closure, so one buffer is reused instead of allocating a String for every row — the same idea as apply_into_string_amortized above, just with two inputs. (see possible solution here)
In the above exercise, we separate the strings with a space, what if the user want another separator string instead of a single space? Here is how we can take an argument provide by the user, in expressions.rs:
use serde::Deserialize;
#[derive(Deserialize)]
struct AddKwargs {
sep: String,
}We use a struct to hold the kwargs, we derive a Deserialize trait for it so we can use it later. This is the same pattern as Accepting kwargs in the user guide. Now we can modify our function for cum_str:
#[polars_expr(output_type=String)]
fn cum_str(inputs: &[Series], kwargs: AddKwargs) -> PolarsResult<Series> {
let s = &inputs[0];
let ca = s.str()?;
let out: StringChunked = ca
.iter()
.scan(
String::new(),
|sentence: &mut String, x: Option<&str>| match x {
Some(x) => {
sentence.push_str(&kwargs.sep);
sentence.push_str(x);
Some(Some(sentence.clone()))
}
None => Some(None),
},
)
.collect();
Ok(out.into_series())
}Adding the kwargs: AddKwargs to the arguments and replace the space ' ' with &kwargs.sep.
Remember to update in __init__.py as well:
def cum_str(expr: IntoExprColumn, sep: str) -> pl.Expr:
return register_plugin_function(
plugin_path=PLUGIN_PATH,
function_name="cum_str",
args=[expr],
is_elementwise=False,
kwargs={"sep": sep},
)By adding the sep: str in the argument and an extra kwargs={"sep": sep} in the register_plugin_function arguments.
Now you can build and try out the new cum_str expression with a different separator string. You may found that the separator string appears at the front of the accumulated string. This may not be desirable, as an extra challenge, could you add an extra argument (a flag) so the user can decide to turn on and off the leading separator strings at the front? (see possible solution here)
This workshop covers elementwise expressions, multiple inputs, dtype dispatch, column-wise accumulation and kwargs. That is enough to write most plugins, but there is more that we have not touched. Here is where to look for each of them.
More expression shapes
- Struct inputs and outputs — reading several fields out of one column, or returning one. See Marco Gorelli's
structchapter. - List and array columns — taking a
ListorArraycolumn as input, and returning one. See the lists and arrays chapters. - Aggregations — an expression that collapses a column to a single value, like a weighted mean. This needs
returns_scalar=Trueinregister_plugin_function, next to theis_elementwiseflag we already use. See the aggregate chapter.
Besides is_elementwise and returns_scalar, register_plugin_function also accepts changes_length, cast_to_supertype and input_wildcard_expansion. They all tell the Polars optimizer how our expression behaves, and they are listed in the API reference.
More on output types
Our same_output_type hand-rolls the "same type as the first input" case. For anything less trivial, polars-plan provides FieldsMapper with helpers such as map_to_float_dtype(), which is what the user guide's haversine_output uses. Note that it lives in polars-plan, not polars, so using it means adding polars-plan = { version = "0.55" } to our Cargo.toml.
There is also a third attribute we have not used: besides output_type and output_type_func, the polars_expr macro accepts output_type_func_with_kwargs, for when the output type depends on the user's keyword arguments as well as the input types. All three are documented in the pyo3-polars README.
Nicer API for our users
Every expression we wrote is called as a plain function, e.g. capitalize("attendees"). Polars can also attach them to a namespace on Expr, so users write pl.col("attendees").my_namespace.capitalize() instead. That is done on the Python side with register_expr_namespace, and the user guide mentions it at the end of its first plugin example.
Generating the type stub instead of writing it
We wrote _internal.pyi by hand, which is fine for one line. Maturin can also generate it from the compiled binary: enable the experimental-inspect feature on our pyo3 dependency, then run maturin generate-stubs -o stubs, or bundle the stub straight into the wheel with maturin build --generate-stubs. This needs maturin 1.15 or newer, and it only works for modules declared as an inline mod — which is exactly the style our lib.rs uses.
There is a wrinkle worth knowing before you reach for it. Introspection cannot see inside a #[pymodule_init] body, so with our current lib.rs it emits def __getattr__(name: str) -> Incomplete: ... instead of __version__: str — which makes every attribute on _internal type-check as Any, weaker than our hand-written line. Declaring the constant directly gives the generator something it can read:
#[pymodule_export]
const __version__: &str = env!("CARGO_PKG_VERSION");which generates __version__: Final[str] properly. The PyO3 user guide's type stub chapter documents all of this, and warns that the feature is still in active development. For a generator that works today on older maturin, see pyo3-stub-gen.
One last thing either way: type checkers ignore stubs shipped in a package that has no py.typed marker, so a distributed plugin wants an empty polars_plugin_101/py.typed file too.
Making it faster, and sharing it
- Our
largeruses amatchon the dtype with one arm per type. The branch mispredictions chapter shows how to think about the cost of per-row branching. - To put a plugin on PyPI so others can
pip installit, see the publishing chapter.
For a wider view, the user guide keeps a list of community plugins — reading a published one is a good way to see how these pieces fit together in a real project.
This workshop is created by Cheuk and is open source for everyone to use (under MIT license). Please consider sponsoring Cheuk's work via GitHub Sponsor.