Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Instantiate a function from string in Python 3.x?

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.

like image 634
alacarter Avatar asked Dec 13 '25 17:12

alacarter


1 Answers

I think you're looking to do exec(my_str, globals()) which will put in the globals dictionary allowing you to access it

like image 60
maor10 Avatar answered Dec 15 '25 06:12

maor10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!