将 Polars API 扩展放入专用模块 - 如何从目标模块导入?

问题描述 投票:0回答:1

我想扩展

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(),
    ]
)
python python-polars
1个回答
0
投票

您可以在

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(),
    ]
)

你可以参考这个例子

© www.soinside.com 2019 - 2024. All rights reserved.