exec
Date: January 5th 2016
Last updated: January 5th 2016
The exec statement (python 2.7) allows dynamic processing of a string. The exec statement is now a function in Python 3.x. Note the exec statement will return nothing if calling a variable, or produce an error if a string is not defined.
exec '42'
# No output
hi = 'print "Hello World"'
exec hi
# output
'Hello World'
On looking into the use of exec I found many warnings about its implementation. The first being that it makes code unreadable. The above code is like defining a function and executing.
# function
def hi():
print 'Hello World'
# run
hi()
If however, the exec statement is used, then there are several things to note. First, it is recommended that the exec statement is not run in its own name space. Make an empty dictionary and process in that. Second, if you are using the code more than once, compile the code to bytecode first before processing (more about bytecode later). Its faster because python will do this on each iteration of the code and it is apparently an expensive operation. Finally, be aware that local and global scoping will effect the output (To see why read the resources below).
# create string for processing
print_string = compile('hi = "Hello World"', '<string>', 'exec')
# create empty dictionary
ns = {}
# exec string in namespace
exec print_string in ns
# call string
print ns['hi']
# Output
'Hello World'
Useful resources:
- http://docs.quantifiedcode.com/python-anti-patterns/security/use_of_exec.html
- http://late.am/post/2012/04/30/the-exec-statement-and-a-python-mystery.html
- http://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python
- http://lucumr.pocoo.org/2011/2/1/exec-in-python/