我想扩展
polars
API,如 docs 中所述,如下所示:
@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")
如果我将实际注册放在专用模块中(
extensions.py
),我该如何从另一个模块中导入相应类的方法?
按照 docs 中的数据帧示例,假设我将以下代码放入名为
target.py
的模块中。greetings
命名空间可用。我该怎么做,即导入应该是什么样子?
pl.DataFrame(data=["world", "world!", "world!!"]).select(
[
pl.all().greetings.hello(),
pl.all().greetings.goodbye(),
]
)
您可以在
import extensions
文件中直接使用 target.py
(假设该文件相对于 target.py
)。这将注册 greetings
命名空间。
import polars as pl
import extensions # noqa: F401
pl.DataFrame(data=["world", "world!", "world!!"]).select(
[
pl.all().greetings.hello(),
pl.all().greetings.goodbye(),
]
)
你可以参考这个例子