Is it possible to create and then reference your own “user functions” in python, within Grist? I am finding myself doing the same things in various tables and columns, and it would be great to centralize this sort of logic to allow reusability and reduce redundant/repetitive code.
As far as I know, Grist doesn’t provide a “proper” way of doing this (unfortunately!). What you can do, however, is to have a separate table to contain your reusable functions, say, “Lib”, and reference that from wherever you need your functions.
This table needs to have formula columns which essentially just return a function object (or even an entire class with methods), like this:
class AmazingFunctions:
def do_something_useful(argument, other_argument):
# do whatever
return 1337
return AmazingFunctions
Place this in a formula column named, e.g. “fn”, and then in your other tables, you can do:
# Nota bene: lookupOne() without any arguments will just return the first record.
# For our purposes, the Lib table will consist entirely of formula columns, so we don't actually need it to contain more than one record anyway.
Lib.lookupOne().fn.do_something_useful("my first argument", "my other argument")
… and it will return 1337.
That’s how I do it for more elaborate projects. Come to think of it, I might release some of my often used “Lib” functions if I get some time… Anyway, hope it helps!
Shoutout to @dmitry-grist and the rest of the team: It would be absolutely amazing if Grist provided a central “reusable user code repository” that could be more easily accessed from formulas. Having just an internal table, say _grist_globalUserCode, might work. A shortcut could be provided for formulas, where you’d simply write something like “Code.your_fn_name_goes_here” and have that translate to “_grist_globalUserCode.lookupOne().your_fn_name_goes_here”.
Also, keep up the great work!
This is a fantastic solution!
For the benefit of others finding this thread, I created a sample doc showing this functionality:
https://docs.getgrist.com/ttbwDBreE9hj/User-Code-SHARED/p/1
… and also +1 for having this built-in, which would be a bit more elegant.
I could foresee a “User Functions” or “User Code” area in the sidebar or Settings, perhaps even with Access Rules support so that you can limit viewing vs editing of the code.
Nice, good idea! I’ll post some of my custom functions over in the showcase in a minute, feel free to add those to your document.