Skip to content

register_dataframe_namespace

laktory.api.register_dataframe_namespace(name) ¤

Decorator for registering a custom namespace on a Narwhals DataFrame.

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_dataframe_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]}))

df = df.custom.with_x2()

print(df)
'''
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
|    | x | x2 |    |
|    |---|----|    |
|    | 0 | 0  |    |
|    | 1 | 2  |    |
└──────────────────┘
'''
References
Source code in laktory/api/namespace.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def register_dataframe_namespace(name: str):
    """
    Decorator for registering a custom namespace on a Narwhals DataFrame.

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

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

    import laktory as lk


    @lk.api.register_dataframe_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]}))

    df = df.custom.with_x2()

    print(df)
    '''
    ┌──────────────────┐
    |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.DataFrame, name, NameSpace(name, ns_cls))
        return ns_cls

    return wrapper