Skip to content

register_dataframe_namespace

laktory.api.register_dataframe_namespace(name) ¤

Decorator for registering custom method to 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/narwhals_ext/namespace.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def register_dataframe_namespace(name: str):
    """
    Decorator for registering custom method to 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