code = "def foo(): return 'bar'" def lol(code): exec code return foo a = lol(code) print a() This works normally, but the problem starts when we don't know what the function in the string is called. If I can guarantee that the code will be small, with a single function, how can I return that function?
One solution I thought of was just requiring the function be called 'foo' etc, so I can just return that, but it feels ugly.
Thoughts?
execfor dynamic code generation is generally frowned upon. I would redesign the code in a way that it does not needexec.