Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for custom function registration #591

Open
jrycw opened this issue Jan 29, 2025 · 0 comments
Open

Support for custom function registration #591

jrycw opened this issue Jan 29, 2025 · 0 comments

Comments

@jrycw
Copy link
Collaborator

jrycw commented Jan 29, 2025

Hello team:

I've been considering how we can help users integrate their custom functions into Great Tables more seamlessly. One possible approach is to introduce register() and unregister() methods (just a rough concept for now), like:

def register(*funcs):
    for func in funcs:
        if hasattr(func, "__name__"):
            func_name = func.__name__
            setattr(GT, func_name, func)


def unregister(*funcs):
    for func in funcs:
        if hasattr(func, "__name__"):
            func_name = func.__name__
            delattr(GT, func_name)

Here’s a simple example:

import polars as pl
from great_tables import GT
from great_tables.data import exibble

df = pl.from_pandas(exibble).select("num", "currency")
shape: (8, 2)
┌──────────┬──────────┐
│ num      ┆ currency │
│ ---      ┆ ---      │
│ f64      ┆ f64      │
╞══════════╪══════════╡
│ 0.1111   ┆ 49.95    │
│ 2.222    ┆ 17.95    │
│ 33.33    ┆ 1.39     │
│ 444.4    ┆ 65100.0  │
│ 5550.0   ┆ 1325.81  │
│ null     ┆ 13.255   │
│ 777000.0 ┆ null     │
│ 8.88e6   ┆ 0.44     │
└──────────┴──────────┘
def fmt_double_plus_n_as_integer(
    self: GT,
    columns: "SelectExpr" = None,
    rows: int | list[int] | None = None,
    plus_n: str | int | float = 1,
) -> GT:
    def fmt_fn(x: str | int | float | None, plus_n: str | int | float = plus_n) -> int:
        if x is None:
            return x
        return int(float(x) * 2 + float(plus_n))

    return self.fmt(fns=fmt_fn, columns=columns, rows=rows)

Currently, users can apply custom functions using GT.pipe(), like:

GT(df).pipe(fmt_double_plus_n_as_integer, columns=["num", "currency"])

Image

However, this feels more like a one-off approach.

For users who heavily rely on custom functions—or for third-party package maintainers working with Great Tables—having register() and unregister() methods could offer greater flexibility and convenience.

register(fmt_double_plus_n_as_integer)

GT(df).fmt_double_plus_n_as_integer(columns=["num", "currency"])

One thing to note is that we may need to consider how to improve modern IDE support to enhance autocomplete functionality in this context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant