How to `eval` code with `def`?

Gregory Ewing greg.ewing at canterbury.ac.nz
Mon May 29 02:39:59 EDT 2017


Peng Yu wrote:
> Does anybody know what is the correct way to evaluation python
> code that contains `def`? Thanks.

Here's one way to do it:

    env = {}
    exec(s, env, env)

Now env['f'] contains the defined function, which you can then
call, disassemble or whatever you want.

-- 
Greg



More information about the Python-list mailing list