In Python, I have a string of some Python source code containing functions like:
mySrc = \'\'\'
def foo():
print(\"foo\")
def bar():
print(\"bar\")
\'\'
You have to both compile and execute it:
myMod = compile(mySrc, '', 'exec')
exec(myMod)
foo()
You can pass dicts to exec
to stop foo
from “leaking” out. Combine it with a module object created using types.ModuleType
:
from types import ModuleType
…
compiled = compile(mySrc, '', 'exec')
module = ModuleType("testmodule")
exec(compiled, module.__dict__)