Code Monkey Monday- Exec(uting) and Eval(uating) Strings in Python

You want to include a little bit of dark magic in your Python coding, right? Well, read on.

More times than I care to admit, I have situations in which I want my code to write more code for me. Because either I am lazy or I need to be tricky. A recent example: I needed to create and populate a list of lists for each week of the NFL season to contain some of my analysis results. With normal coding, I saw two options: copy paste my code 21 times (17 regular season weeks and 4 playoff weeks) or create a confusing list of list of lists of results. Because the analysis was consistent over the weeks, there was a third option that I preferred: using the exec() and eval() statements.

exec(string) takes a string and executes it like it was a full line of code. So exec(“list”+str(week)+”=[]”) would execute different things depending on the value of week:
If week==1, the line would be: list1=[]
If week==2, the line would be: list2=[]
etc. It basically substitutes the value of week into the string and then executes what the string says.

By cycling through the weeks of the season, I created an empty list for each week using exec:
for week in weeks:

2 lines of code to create 21 lists instead of 21.

I later populated the list with something like: exec(“list”+str(week)+”.append(results)”)

The eval(string) turns the string into code and then allows it to be used in a larger code statement. For example: output+=eval(“list”+week+”[i]”)
This creates the code line
if week==1. In this way, I can add the i’th component of each week’s list to some output string that I saved.

There are more exotic uses of exec() and eval() that I’ve used in the past. Someday I’ll write about how we created code to parse and evaluate any Google Protocol Buffer (kind of like xml) at Booz Allen.

Disclaimer: exec() and eval() may not be “good practice” for a professional coder, but I’m not a professional coder and just create code that works for me.

Leave a Reply

Your email address will not be published. Required fields are marked *