exec(code) not allowing import on top level?

Peter Teuben teuben at verizon.net
Tue Jul 29 05:26:45 CEST 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