I want to extend polars
API as described in the docs, like this:
@pl.api.register_expr_namespace("greetings")
class Greetings:
def __init__(self, expr: pl.Expr):
self._expr = expr
def hello(self) -> pl.Expr:
return (pl.lit("Hello ") + self._expr).alias("hi there")
def goodbye(self) -> pl.Expr:
return (pl.lit("Sayōnara ") + self._expr).alias("bye")
If I were to put the actual registration in a dedicated module (extensions.py
), how am I supposed to import the methods from the respective class from within another module?
Going with the dataframe example in the docs, let's say I put the following code in a module called target.py
.
I need to make the greetings
-namespace available. How can I do it, i.e. how excactly should the import look like?
pl.DataFrame(data=["world", "world!", "world!!"]).select(
[
pl.all().greetings.hello(),
pl.all().greetings.goodbye(),
]
)
You could just import extensions
(assuming that the file is relative) in your target.py
file to register the greetings
namespace.
import polars as pl
import extensions # noqa: F401
pl.DataFrame(data=["world", "world!", "world!!"]).select(
[
pl.all().greetings.hello(),
pl.all().greetings.goodbye(),
]
)
See also: