pitfall for your amusement

Terry Hancock hancock at anansispaceworks.com
Tue Nov 12 21:52:02 EST 2002


On Tuesday 12 November 2002 12:46 pm, python-list-request at python.org wrote:
> If you are collecting pitfalls, here's my least favorite: "never use a 
> mutable object as a default value". A classic example:
> 
> def badfunc(alist=[]):
>    ...
> 
> The default value of alist will not stay [] (an empty list) but instead 
> is affected by whatever you pass in for "alist". Very tricky and 
> unpleasant.
> 
> Here's my usual solution:
> def okfunc(alist=None):
>    alist = alist or []
>    ...

Hmm. I don't see this:

>>> def spam(eggs, ham=[]):
...     print "%s and %s" % (eggs, ham)
... 
>>> spam('eggs')
eggs and []
>>> spam('eggs', 'ham')
eggs and ham
>>> spam('eggs')
eggs and []
>>> spam('eggs', ham=['more ham'])
eggs and ['more ham']
>>> spam('eggs')
eggs and []
>>> spam('eggs', ham=['more ham'])

What would I have to do for this to be a problem? (as it happens, I have used 
this kind of default before, so I would like to understand the pitfall!)

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list