Why the result

Bruno Desthuilliers onurb at xiludom.gro
Fri Oct 20 05:25:47 EDT 2006


HYRY wrote:
> Why the third print stement output "'comments': [(1, 2, 3)]", I think
> it should be [].
> I am using
> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
> on win32.
> 
> # program
> class PicInfo:
>     def __init__(self, intro="", tags="", comments=[]):

This is a FAQ - and one of the most (in)famous Python's gotchas. Default
arguments are eval'd *only once* - when the def statement is eval'd,
which is usually at import time. So using a mutable object as default
value makes this object behaving somehow like a C 'static' local
variable, ie it keeps it value from call to call.

The canonical idiom is to use None instead:

class PicInfo(object):
  def __init__(self, intro="", tags="", comments=None):
    self.picintro = intro
    self.pictags = tags
    if comments is None:
      comments = []
    self.comments = comments

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list