exec(code) not allowing import on top level?

Peter Teuben teuben at verizon.net
Mon Jul 28 23:26:45 EDT 2008


if I define a simple string code, with the following contents:

import math
def foo(x):
   return math.sqrt(x)

and i run it using exec(code) in python, math is not known. But when I
recode the string as:

def foo(x):
   import math
   return math.sqrt(x)

it works fine. That seemed like an inconsistency, since it works
fine otherwise, as expected. It's easy to work around, but
just odd to find this out.

thanks

	peter



More information about the Python-list mailing list