[Python-ideas] Have list/deque grow a copy() method

Ian D. Bollinger ian.bollinger at gmail.com
Tue May 15 16:53:57 CEST 2007


It would be nice if containers had a more consistent interface. The
standard idiom for copying a list has been L[:], but this isn't
polymorphic and perhaps arcane. Also, deques can only be copied with the
copy module's copy function (or calling the __copy__ wrapper directly);
thus using copy.copy is the only polymorphic way to copy a mutable
container. Additionally, having a consistent interface for mutable
containers may dovetail with the ABC PEP.

An alternate proposal would be to move copy.copy (and perhaps
copy.deepcopy) into __builtins__. (Though this might be nice
regardless.)

As an aside, in addition to the copy method, list is the only mutable
container not to have a clear method. Of course, del L[:] is the
standard idiom for doing so, but this has the same problem of not being
polymorphic. Perhaps having both del L[:] and L.clear() would violate
the TOOWTDI principle, but L.reverse() can also be done with L = L[::-1]
(maybe not the best example since they have different semantics.)
Nevertheless, one is a lot easier to read.

As for a use case, one might be a class that generalizes how it stores
elements.  For instance...

class MutableUnorderedTree(AbstractTree):
    _storage_class = set

class MutableOrderedTree(AbstractTree):
    _storage_class = list

...the latter has to be adapted to ensure consistent interface for
methods like copy/clear.

Well, that's my crackpot idea for today.
- Ian D. Bolligner




More information about the Python-ideas mailing list