Skip to content

Instantly share code, notes, and snippets.

@thehappycheese
Created July 28, 2022 03:04
Show Gist options
  • Save thehappycheese/0b74f19b581f7f2f58dba364e17693dc to your computer and use it in GitHub Desktop.
Save thehappycheese/0b74f19b581f7f2f58dba364e17693dc to your computer and use it in GitHub Desktop.
Compile a python function from string, and return the function
# Take a snippet of python code that defines at least one function at the top-level, then returns the last defined function.
import ast
def compile_function(source:str):
# parse first, so we can automatically find the funciton name later
parsed = ast.parse(source)
# compile in specified `scope` dictionary
exec(compile(source, "", "exec"), scope:={})
# return the last function definition
for item in reversed(parsed.body):
if isinstance(item, ast.FunctionDef):
return scope[item.name]
raise Exception("No function definition found in source")
#----------------------------------------------------------------
# example usage
mf = compile_function("""
import pandas as pd
def do_thing(a:int):
return a+2
def myfunc(a:int, b:str):
x = str(do_thing(a))+b+b
return pd.Series([x]*3)
""")
mf(1,"a")
# 0 3aa
# 1 3aa
# 2 3aa
# dtype: object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment