Re: exec(code) not allowing import on top level?

2008-07-29 Thread Peter Otten
Peter Teuben wrote: > > if I define a simple string code, with the following contents: > > import math > def foo(x): >return math.sqrt(x) The import math statement puts 'math' in the local namespace, and foo looks it up in the global namespace. This can only work when these namespaces a

Re: exec(code) not allowing import on top level?

2008-07-29 Thread Steven D'Aprano
On Tue, 29 Jul 2008 03:26:45 +, 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(

Re: exec(code) not allowing import on top level?

2008-07-28 Thread Gary Herron
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.Sec

Re: exec(code) not allowing import on top level?

2008-07-28 Thread Gary Herron
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.Sec

exec(code) not allowing import on top level?

2008-07-28 Thread Peter Teuben
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 inconsis