[Python-ideas] clear() method for lists

Stephen J. Turnbull turnbull at sk.tsukuba.ac.jp
Fri Feb 12 03:54:07 CET 2010

Gerald Britton writes:

 > Thanks all for helping me understand this better.  The subtly above is
 > something I missed.  I searched the doc for a description of it but
 > couldn't readily find it.  Tim's simple one-line statement and the
 > example above does it very nicely.

It's in the language reference.  It is only two lines (the definition
of "immutable" and the description of assignment semantics), so easy
to miss. :-)  There probably is some discussion in the tutorial.

 > Switching gears for a moment, what is the feeling regarding the copy()
 > methods for dictionaries and sets?  Are they truly redundant?  Should
 > they be deprecated?  Should users be encouraged to use the copy module
 > or just  use "newdict = dict(olddict)" and "newset = set(oldset)" to
 > build a new dictionary or set from an existing one?

I think they are redundant.  new = type(old) should be the standard
idiom for an efficient shallow copy.  If that doesn't serve your
application's needs, use the copy module.  The responsibility for
discrimination is the application programmer's.  Superficially this
might seem to violate TOOWTDI, but actually, not.  Shallow copies and
deep copies are two very different "Its", and have to be decided by
the app author in any case.

I don't see what .copy can add.

.clear is another matter, in terms of semantics.  However, the same
effect can be achieve at the cost of indirection and extra garbage:

class DictWithClear(object):
    def __init__(self):

    def clear(self):
        d = {}

    # Implement other dict methods here.

This is obviously wasteful if all you want to do is add .clear to a
"bare" dictionary.  However, in many cases the dictionary is an
attribute of a larger structure already and the only direct reference
to the dictionary is from that structure.  Then clearing by replacing
the obsolete dictionary with a fresh empty one is hardly less
efficient than clearing the obsolete contents.

There are other arguments *for* the .clear method (eg, it would be a
possibly useful optimization if instead of a class with a dictionary
attribute, the class inherited from the dictionary).

More information about the Python-ideas mailing list