exec(code) not allowing import on top level?

Gary Herron gherron at islandtraining.com
Tue Jul 29 06:18:24 CEST 2008


Peter Teuben wrote:
>
> if I define a simple string code, with the following contents:
>
> import math
> def foo(x):
>   return math.sqrt(x)

What?  You have not told us something important here.  First, that code 
won't fail because it does not even execute the function foo -- it just 
defines it.    Second, if I extended your string with one more line 
"foo(123)" to actually execute the code, it still works as expected.

So let's try this again...  and this time please please also show us the 
full text of the error message.

Gary Herron


>
> 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
> -- 
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list