Skip to content

register_expr_namespace

laktory.api.register_expr_namespace(name) ¤

Decorator for registering a custom namespace on 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/api/namespace.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def register_expr_namespace(name: str):
    """
    Decorator for registering a custom namespace on 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