Skip to content

register_expr_namespace

laktory.api.register_expr_namespace(name) ¤

Decorator for registering custom method to a Narwhals Expression.

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_expr_namespace("custom")
class CustomNamespace:
    def __init__(self, _expr):
        self._expr = _expr

    def double(self):
        return self._expr * 2


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

df = df.with_columns(x2=nw.col("x").custom.double())

print(df)
'''
┌──────────────────┐
|Narwhals DataFrame|
|------------------|
|    | x | x2 |    |
|    |---|----|    |
|    | 0 | 0  |    |
|    | 1 | 2  |    |
└──────────────────┘
'''
References
Source code in laktory/narwhals_ext/namespace.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def register_expr_namespace(name: str):
    """
    Decorator for registering custom method to a Narwhals Expression.

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

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

    import laktory as lk


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

        def double(self):
            return self._expr * 2


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

    df = df.with_columns(x2=nw.col("x").custom.double())

    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.Expr, name, NameSpace(name, ns_cls))
        return ns_cls

    return wrapper