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:

def exec_code(co):
        exec co
        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,))
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
 exec from thread - no global

 exec code2 - with global
 exec from thread - with global
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.


More information about the Python-list mailing list