exec and global puzzle

Andr? Roberge andre.roberge at ns.sympatico.ca
Mon Dec 6 03:37:08 CET 2004


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



More information about the Python-list mailing list