exec(code) not allowing import on top level?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Jul 29 04:43:36 EDT 2008


On Tue, 29 Jul 2008 03:26:45 +0000, Peter Teuben wrote:

> 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.


Works for me.


>>> code = """import math
... def foo(x):
...     return math.sqrt(x)
... """
>>>
>>> exec code 
>>> foo(25)
5.0

By the way, exec is a statement, not a function, so you don't need the 
brackets.



-- 
Steven



More information about the Python-list mailing list