assignment in python

So I burned about an hour untangling some problem in a python script. Turns out that the root cause was that I was using a template dict to populate with config variables, but because variables are essentially references in python, you need to be careful when doing this. For example:

BASELINE = {
    "option1": None,
    "option2": None,
    "option3": None,
}

for i in instances:
    i = BASELINE
    i['option1'] = figure_out_option()
    [etc]

In the first iteration of that for loop, variables i and BASELINE point to the same object, so changes to i affect BASELINE as well. Whoops. To get around this, you can either use the copy function in the copy module, or in this case with a dict, just use the copy method, eg:

for i in instances:
    i = BASELINE.copy()
    [etc]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s