473,322 Members | 1,403 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

exec(code) not allowing import on top level?


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
Jul 29 '08 #1
4 1076
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 exend 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
Jul 29 '08 #2
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
Jul 29 '08 #3
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
Jul 29 '08 #4
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 are the same:
>>code = """
.... import math
.... def foo(x):
.... return math.sqrt(x)
.... print foo(2)
.... """
>>exec code in {}
1.41421356237
>>exec code in {}, {}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 5, in <module>
File "<string>", line 4, in foo
NameError: global name 'math' is not defined

You could argue that Python should always look into the local namespace and
then fall back to the global namespace but that would be fruitless extra
work in most cases. I think it can only hapen with exec/eval, and as you
have seen in the other responses even there it works on the module level
because -- tada!
>>globals() is locals()
True
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)
Here Python "guesses" that math is a local variable and that guess is
correct. If you wrote

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

Python would still guess that math is a local name and you would end up with
a runtime exception.

Peter
Jul 29 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Gerald Senarclens de Grancy | last post by:
Hi! I kept searching my online and offline python ressources to figure out how to execute some code in the global dictionary. Basically I'm reading a options file that defines some variables. I...
1
by: arice | last post by:
I need to create a timer and begin processing tasks in my asp.net code when IIS starts or restarts. I do not know of any way to execute even my global procedures without some external application...
4
by: carl.dhalluin | last post by:
Hello I am completely puzzled why the following exec code does not work: mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" def execute(): exec mycode execute()
0
by: Stef Mientki | last post by:
Terry Reedy wrote: sorry, don't know how this happened, as I always copy/paste ? AFAIK locals() == sys._getframe(0).f_locals AFAIK, again one level up weird, I use it in 2.5 and if I remember...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.