简体   繁体   中英

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.

我想你正在寻找exec(my_str, globals()) ,它将放入全局字典中,允许你访问它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM