Skip to content

Instantly share code, notes, and snippets.

@minghan
Created July 8, 2011 18:37
Show Gist options
  • Save minghan/1072475 to your computer and use it in GitHub Desktop.
Save minghan/1072475 to your computer and use it in GitHub Desktop.
Python Compile and Exec test
# Compile and Exec test
# Just making sure that exec deals with scoping correctly
#
# Note that the compile statement compiles code into bytecode, but does not execute it
# Reference: http://lucumr.pocoo.org/2011/2/1/exec-in-python/
def pakrox2():
print "pakrox2 external"
code = ""
def test():
s = "def pakrox():\n"
s += "\tprint 1+1\n"
def pakrox2():
print 'pakrox2 internal'
s += "pakrox()\n"
s += "pakrox2()\n"
global code
code = compile(s, '<string>', 'exec')
exec code # should print 'pakrox 2 internal'
test()
exec code # should print 'pakrox 2 external'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment