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

Terry Reedy tjreedy at udel.edu
Thu Jun 25 20:02:53 CEST 2009

Nick Coghlan wrote:

> My suggestions:
> 1. Make it a class method "from_list". Document its semantics as
> something like:
>   @classmethod
>   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).

Suppose 'fromlist' literally meant from 'from a list object' and not 
from list subclasses. Would not that be clearly safe?

Kristján, would that restriction be okay for your purposes, or do you 
really need from subclass to subclass?

> 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
> direction.
> Cheers,
> Nick.

More information about the Python-ideas mailing list