[Discuss] Compiling/running user-supplied Python code

Brian Quinlan brian at sweetapp.com
Thu Aug 10 11:15:19 PDT 2006


Adam Parkin wrote:
> Any suggestions?

 >>> code_ns = {}
 >>> code = "def foo(n):\n\tx = 3 * n\n\treturn x\n"
 >>> trigger = "foo(5)"
 >>> exec code in code_ns
 >>> eval(trigger, code_ns)
15

The "code_ns" idea is not necessary but I think that it is desirable to 
separate your programs global namespace from that of the external code 
e.g. so that they can't accidentally define a symbol that overrides one 
of yours.

Cheers,
Brian


More information about the Discuss mailing list