473,417 Members | 1,628 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,417 software developers and data experts.

exec and global puzzle

I have the following two files:

#--testexec.py--
def exec_code(co):
try:
exec co
except:
print "error"

#-- test.py--
import thread
import testexec
import time

code = "def a():\n print 'a'\n\n" +\
"def c():\n a()\n\nc()"

code2 = "def a():\n print 'a'\n\n" +\
"def c():\n global a\n a()\n\nc()"

print " exec code - no global"
exec code
print " exec from thread - no global"
thread.start_new(testexec.exec_code, (code,))
time.sleep(1)
print "\n exec code2 - with global"
exec code2
print " exec from thread - with global"
thread.start_new(testexec.exec_code, (code2,))
#-----------------------

Here's the output when I execute test.py:

exec code - no global
a
exec from thread - no global
error

exec code2 - with global
a
exec from thread - with global
a
#---------
Without the global statement, I get an error when trying to execute
the code.
I don't understand why I need to use the global statement within the
definition of c() in order for it to know what a() is. If I define
exec_code() within test.py and use it there, I do not get any error,
with or without the use of a global statement.

Andre
Jul 18 '05 #1
1 2209
Andr? Roberge wrote:
I have the following two files:

#--testexec.py--
def exec_code(co):
try:
exec co
except:
print "error"

#-- test.py--
import thread
import testexec
import time

code = "def a():\n print 'a'\n\n" +\
"def c():\n a()\n\nc()"

code2 = "def a():\n print 'a'\n\n" +\
"def c():\n global a\n a()\n\nc()"

print " exec code - no global"
exec code
print " exec from thread - no global"
thread.start_new(testexec.exec_code, (code,))
time.sleep(1)
print "\n exec code2 - with global"
exec code2
print " exec from thread - with global"
thread.start_new(testexec.exec_code, (code2,))
#-----------------------

Here's the output when I execute test.py:

exec code - no global
a
exec from thread - no global
error

exec code2 - with global
a
exec from thread - with global
a
#---------
Without the global statement, I get an error when trying to execute
the code.
I don't understand why I need to use the global statement within the
definition of c() in order for it to know what a() is. If I define
exec_code() within test.py and use it there, I do not get any error,
with or without the use of a global statement.

Andre


I have taken the liberty of restructuring your program slightly, by
using a "from" to explicitly import the function you need, and by using
extended string literals (""" ... """) to make the code easier to read.
I have also included print statements to show the contents of the local
and global namespaces after the definition of function a(). After these
transformations it looks like this:

import thread
from testexec import exec_code
import time

code = """\
def a():
print 'a'

def c():
a()

c()
"""

code2 = """\
def a():
print 'a'

def c():
global a
a()

c()
"""

print " exec code - no global"
exec code
print " exec from thread - no global"
thread.start_new(exec_code, (code,))
time.sleep(1)
print "\n exec code2 - with global"
exec code2
print " exec from thread - with global"
thread.start_new(exec_code, (code2,))
time.sleep(1)

(OK, I added a final sleep so I saw the output from the second thread).

The reason you are seeing this behavior lies in the behavior of the exec
statement. The full syntax for that statement is

exec_stmt ::= "exec" expression ["in" expression ["," expression]]

The second and third expressions are mappings that will be used as
namespaces. Since you don't provide either, the interpreter uses the
current scope (whose contents can be determined using the locals()
function) for both namespaces, so it doesn't matter whether the function
is added to the local or the global namespace.

When using threads, however (and, by the way, the usual advice is to use
the threading module, which has a more convenient API), the namespaces
are clearly different. The a() function is being added to the local
namespace for the exec.

So ultimately it's to do with namespaces, as many of the more perplexing
problems in Python are. I hope this helps establish exactly *why* you
see what you do.

regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
Jul 18 '05 #2

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

Similar topics

1
by: Jimmy Jim | last post by:
Hey all, quick question to see if anyone has any ideas. I have an object: $special = new special; Let's say I have a function: class special { function outputtext() { return "test";
2
by: Greg Chapman | last post by:
I am at my wit's end trying to get information out of Streamline.net's support dept about my problem. They reply quickly enough, but seem to try and give out the least possible amount of info each...
2
by: Jonathan | last post by:
I'm puzzled by Python's behavior when binding local variables which are introduced within exec() or execfile() statements. First, consider this simple Python program: # main.py def f() : x = 1...
5
by: Nick Jacobson | last post by:
This works fine: x = 1 def execfunc(): print x execfunc() So why doesn't this? s = \
2
by: N. Pourcelot | last post by:
Hello, I can't understand some specific behaviour of the exec statment. For example, say that I create such a class A : class A: def __init__(self): self.n = 3 self.m = None def h(self,...
10
by: Antoon Pardon | last post by:
I have the following little piece of code: class Cfg:pass #config = Cfg() def assign(): setattr(config, 'Start' , ) def foo(): config = Cfg()
1
by: Crutcher | last post by:
I've been playing with dictionary subtypes for custom environments, and I encountered a strange interaction between exec, dictionary subtypes, and global variables. I've attached a test program,...
21
by: comp.lang.tcl | last post by:
set php {<? print_r("Hello World"); ?>} puts $php; # PRINTS OUT <? print_r("Hello World"); ?> puts When I try this within TCL I get the following error:
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.