Skip to content

register_anyframe_namespace

laktory.api.register_anyframe_namespace(name) ¤

Decorator for registering a custom namespace on a Narwhals DataFrame and 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_anyframe_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
def register_anyframe_namespace(name: str):
    """
    Decorator for registering a custom namespace on a Narwhals DataFrame and LazyFrame.

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

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

    import laktory as lk


    @lk.api.register_anyframe_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))
        setattr(nw.LazyFrame, name, NameSpace(name, ns_cls))
        return ns_cls

    return wrapper