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

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:

results matching ""

    No results matching ""