Skip to content

register_lazyframe_namespace

laktory.api.register_lazyframe_namespace(name) ¤

Decorator for registering a custom namespace on a Narwhals LazyFrame.

PARAMETER DESCRIPTION
name

Name of the namespace.

TYPE: str

Examples:

import narwhals as nw
import polars as pl

import laktory as lk


@lk.api.register_lazyframe_namespace("custom")
class CustomNamespace:
    def __init__(self, _df):
        self._df = _df

    def with_x2(self):
        return self._df.with_columns(x2=nw.col("x") * 2)


df = nw.from_native(pl.DataFrame({"x": [0, 1]}).lazy())

df = df.custom.with_x2()

print(df.collect().sort("x"))
'''
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
|    | x | x2 |    |
|    |---|----|    |
|    | 0 | 0  |    |
|    | 1 | 2  |    |
└──────────────────┘
'''
References
Source code in laktory/api/namespace.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def register_lazyframe_namespace(name: str):
    """
    Decorator for registering a custom namespace on a Narwhals LazyFrame.

    Parameters
    ----------
    name:
        Name of the namespace.

    Examples
    -------
    ```py
    import narwhals as nw
    import polars as pl

    import laktory as lk


    @lk.api.register_lazyframe_namespace("custom")
    class CustomNamespace:
        def __init__(self, _df):
            self._df = _df

        def with_x2(self):
            return self._df.with_columns(x2=nw.col("x") * 2)


    df = nw.from_native(pl.DataFrame({"x": [0, 1]}).lazy())

    df = df.custom.with_x2()

    print(df.collect().sort("x"))
    '''
    ┌──────────────────┐
    |Narwhals DataFrame|
    |------------------|
    |    | x | x2 |    |
    |    |---|----|    |
    |    | 0 | 0  |    |
    |    | 1 | 2  |    |
    └──────────────────┘
    '''
    ```

    References
    ----------
    * [Narwhals Extension](https://www.laktory.ai/concepts/extension_custom/)
    """

    def wrapper(ns_cls: type):
        setattr(nw.LazyFrame, name, NameSpace(name, ns_cls))
        return ns_cls

    return wrapper