[Python-ideas] add a list.swap() method

Nick Coghlan ncoghlan at gmail.com
Thu Jun 25 12:32:55 CEST 2009

Kristján Valur Jónsson wrote:
> So, maybe I should rephrase the "idea."
> The idea is for example to speed up the initialization of lists (and subclasses of lists) from other lists when the source list's contents is to be discarded.  The semantics of
> a.swap(b)
> are the same as
> a[:], b[:] = b[:], a[:]
> but it 
> a) is orders of magnitude faster
> b) skips any special methods (such as __setslice__) and so may break class invariants of list subclasses, as pointed out on this list.

As Raymond posted, the potential breakage is a major downside (and
almost certainly a deal breaker without some safety rails, and possibly
still a deal breaker even with them). The name also concerns me, since I
think it is misleading as to the intended usage of the method.

My suggestions:

1. Make it a class method "from_list". Document its semantics as
something like:

  def from_list(cls, other):
    """Fast but destructive conversion of a list instance
       to a different type of list instance"""
    self = cls()
    self[:] = other[:]
    other[:] = []
    return self

2. Put in some safety rails, similar to what we do to prevent hashing of
classes that override __eq__ without overriding __hash__. If __setitem__
and __setslice__ on cls or other aren't the same as the base class
definitions, don't allow the operation to proceed (i.e. throw a
TypeError saying that the operation needs list instances that use the
standard value setting semantics).

3. Possibly provide some C API level tools to make it easier for a list
subclass to write their own fast constructor based on this idea

I'm not sure it is actually practical to make munging about with list
internals like this "safe" enough to be comfortably exposed at the
Python level, but ideas like the above would at least be a step in that


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list