r/learnpython • u/anothernaturalone • Sep 17 '26
How to let users define their own functions
I am coding a CLI to help users work with the OpenReview API and download/analyse data from it. I want to make the CLI a package, as in https://typer.tiangolo.com/tutorial/package/ (I'm using typer), but one feature I really want may not allow that.
OpenReview data is complex in format and tricky to work with, and I can only offer a list of basic statistics for the stats part of my CLI to analyse. This is the code for that (just for reference, it's terrible code but it works and I can improve upon it later):
funcs = [
[year, 1, "year"],
[decision, 1, "decision"],
[num_authors, 1, "num_authors"],
[total_word_count, 3, "word_count"],
[all_scores, 2, "scores"],
[a_replies, 0, "author_replies"],
[r_replies, 0, "reviewer_replies"]
]
def format(paper: dict, scores: list[str]) -> str:
try:
chains = create_chains(paper)
except:
return ""
ls = []
for x in funcs:
if x[1] == 1:
ls.append(x[0](paper))
elif x[1] == 2:
ls.extend(x[0](chains, scores))
elif x[1] == 3:
ls.append(x[0](chains, scores))
else:
ls.append(x[0](chains))
return_str = ""
for i, review in enumerate(chains):
return_ls = [str(x[i]) if isinstance(x, list) else str(x) for x in ls]
return_str += ",".join(return_ls)
return_str += "\n"
return return_strI want the user, when they make a database (folder structure for the data, in readable format so they can access it at any time and use it for something that isn't my program), to get a python file inside it that they can write their own statistics functions in, and when format_all (a function that does format for a lot of things) is run, their functions are added to the list. Is there any way to allow the CLI package to read functions from a py file and use them?