Saturday, November 14, 2009

Python: Function Argument Default Value Gotcha

Nothing new for experienced python developers, but really annoying for beginners. Try this piece of code:


The output of this will be:


Dude, what just happened? See, python calculates function arguments' default values on function definition time. So our default argument list is actually a reference that never changes. Hence we always modify same variable when calling append with default list.
Even knowing the pythons execution model this is one of those things that can cause what I call a "sweet wtf moment" and make you start a debugger. Which you of course hate doing cause you're TDDing, right? :)

Workaround? Sure:


More info in Python Manual.



Download source code of examples in this post.

0 comments: