How do I instantiate a function from a string in Python 3.x?
I have a string with the full text of a function :
my_str = 'def my_fn(a, b):\n return a+b'
I want my program to be able to instantiate my_func
, save it to an object, and call it later.
exec(my_str)
returns <function my_fn at ... >
viewed on the command line, it is undefined
at runtime. eval(my_str)
returns SyntaxError: invalid syntax
is not really what I want anyway.
I’m confused here. How do I get my function variable from this string?
It would be a nice bonus if I could later rename the function to something else (didn’t know its name at first).
Note: I know it’s dangerous to use exec
. If there is a better way to do this, I am open to suggestions. For now, this is just a research code. It runs locally, I show people how to use it, it doesn’t run on the internet.
Solution
I think you want to do it
exec(my_str, globals())
It will be put into a global dictionary, allowing you to access it