I have a string, which contains the full text of a function:
my_str = 'def my_fn(a, b):\n return a+b'
I would like my program to be able to instantiate my_func, save it to an object and call it later.
exec(my_str) returns a <function my_fn at ...> when viewed in the command line, but is undefined at runtime. eval(my_str) returns a SyntaxError: invalid syntax and isn't really what I want anyway.
I'm confused here. How can I get my function variable from this string?
It would be a nice bonus if I could rename the function to something else later (without knowing its name at first).
note: I'm aware that using exec is dangerous. If there are better ways to do this, I'm open to suggestions. For the moment, this is just a research code. It's run locally, I show people how to use it and it isn't going on the internet.
I think you're looking to do
exec(my_str, globals())
which will put in the globals dictionary allowing you to access it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With