Something C programmers should not write in Python code

September 29, 2005

In C, a common idiom for initializing multiple variables to the same value is serial assignment:

a = b = c = 0;

Python allows for the same thing; just remove the semicolon in the above and it's valid Python syntax, and it even works. So when I was starting Python, I wrote things like that. And then one day I wrote almost the same thing, in an __init__ function in a class:

self.fooDict = self.barDict = {}

The resulting debugging experience was very educational.

A C programmer expects multiple assignment to work using what I'll call 'value semantics', where the result of an assignment is a value and that value is then copied into the next variable. Thus, I'd (subconsciously) expected the Python assignment to be the same as:

self.fooDict = {}
self.barDict = {}

However, Python operates using reference semantics; the result of an assignment is merely another reference to what was assigned, so the next variable just gets another reference to the same thing. In other words, what I was actually getting was the same as:

self.barDict = {}
self.fooDict = self.barDict

Since my code required the two dictionaries to be distinct, and used the same keys in both, the result didn't work too well. (It also caused me to spend some time trying to hunt down where various strange entries were getting added to each dictionary before the penny dropped.)

I was led down this garden path partly because this does 'work' in the case of multiple assignment of a lot of simple Python things (including numbers). This is because they're immutable. If the object one variable points at can't change, it doesn't matter how many other people also point at it; the value can't change out from underneath you.

Written on 29 September 2005.
« MSNbot goes crazy with RSS feeds
Pinging in Python »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Thu Sep 29 00:39:52 2005
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.