Python Thought of the Day

Even experienced Python developers get bitten by the old mutable-default trick. Since function defaults are evaluated at the time the def statement is executed, you might run into some surprising behavior:

>>> def blop(blat=[]):
...     blat.append('derp')
...     return blat
...
>>> blop()
['derp']
>>> blop()
['derp', 'derp']
>>> blop()
['derp', 'derp', 'derp']

For developers unaware of how Python code is evaluated, this kind of bug can seem like a real "gotcha." The ever-common solution, if a new list is to be the default, is:

>>> def blop(blat=None):
...     if blat is None:
...         blat = []
...     blat.append('derp')
...     return blat
...
>>> blop()
['derp']
>>> blop()
['derp']
>>> blop()
['derp']

It's amazing how often this kind of thing shows up; it certainly took me a few wild-goose chases of bug hunts before this became a reflex.