Skip to content

Instantly share code, notes, and snippets.

@williambdean
Last active September 19, 2025 15:28
Show Gist options
  • Save williambdean/aa05e30b923270e379df8950f54b3659 to your computer and use it in GitHub Desktop.
Save williambdean/aa05e30b923270e379df8950f54b3659 to your computer and use it in GitHub Desktop.
function decorator to extend polars with new method via dataframe namespace accessors
"""Example of adding new methods to Polars DataFrames using decorators and namespace accessors.
Examples
--------
Make a new method that doubles all values in a DataFrame:
.. code-block:: python
import polars as pl
@new_method
def double(df: pl.DataFrame) -> pl.DataFrame:
return df * 2
df = pl.DataFrame(
{
"a": [1, 2, 3],
"b": [4, 5, 6],
}
)
df.double()
References:
- https://docs.pola.rs/api/python/stable/reference/api.html
"""
import polars as pl
from functools import wraps
def new_method(func):
"""A decorator to add a new method to DataFrames."""
name = func.__name__
@pl.api.register_dataframe_namespace(name)
class NewNameSpace:
def __init__(self, df: pl.DataFrame):
self._df = df
@wraps(func)
def __call__(self, *args, **kwargs):
return func(self._df, *args, **kwargs)
return func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment