I came across few related answers but not what I want.
Here is the code I have now:
code_str = """
print "this is my global x = " + x
print "And another line is done"
"""
x = 'mystery'
func_template = lambda p: None
func_template.__code__ = compile(code_str, '<string>', 'exec')
func_template() # this executes fine and also has access to x, which i do need.
# func_template('param') # This raises: TypeError: <module>() takes no arguments (1 given)
Some background; The code_str will be coming from a database, and I need to store lots of functions in a dict so I can call any one by name, like below:
all_funcs = {}
# Assuming db_result returns a list of name, code tuples from the databse
for name, code in db_result:
all_funcs[name] = my_compile(code)
I want to then just call the needed function with the arguments I want if I know the name:
result = all_funcs[by_name](arg1, arg2)
Edit: database is trusted, so I do not need to santize or worry about malicious code.