Python 2.x gotcha's and landmines
Question: The purpose of my question is to strengthen my knowledge base with Python and
get a better picture of it, which includes knowing its faults and surprises.
To keep things specific, I'm only interested in the CPython interpreter.

I'm looking for something similar to what learned from my [PHP
landmines](http://stackoverflow.com/questions/512120/php-landmines-in-general)
question where some of the answers were well known to me but a couple were
borderline horrifying.

Update: Apparently one maybe two people are upset that I asked a question
that's already partially answered outside of Stack Overflow. As some sort of
compromise here's the URL <http://www.ferg.org/projects/python_gotchas.html>

Note that one or two answers here already are original from what was written
on the site referenced above.


Answer: **Expressions in default arguments are calculated when the function is
defined,_not_ when it’s called.**

**Example:** consider defaulting an argument to the current time:

    
    
    >>>import time
    >>> def report(when=time.time()):
    ...     print when
    ...
    >>> report()
    1210294387.19
    >>> time.sleep(5)
    >>> report()
    1210294387.19
    

The `when` argument doesn't change. It is evaluated when you define the
function. It won't change until the application is re-started.

**Strategy:** you won't trip over this if you default arguments to `None` and
then do something useful when you see it:

    
    
    >>> def report(when=None):
    ...     if when is None:
    ...         when = time.time()
    ...     print when
    ...
    >>> report()
    1210294762.29
    >>> time.sleep(5)
    >>> report()
    1210294772.23
    

**Exercise:** to make sure you've understood: why is this happening?

    
    
    >>> def spam(eggs=[]):
    ...     eggs.append("spam")
    ...     return eggs
    ...
    >>> spam()
    ['spam']
    >>> spam()
    ['spam', 'spam']
    >>> spam()
    ['spam', 'spam', 'spam']
    >>> spam()
    ['spam', 'spam', 'spam', 'spam']
    

