[Python-ideas] add a list.swap() method
Steven D'Aprano
steve at pearwood.info
Fri Jun 26 02:41:29 CEST 2009
On Fri, 26 Jun 2009 08:37:36 am Kristján Valur Jónsson wrote:
> Since I started uncovering list bad-boys, I think perhaps list.pop()
> might be the evilest of the bunch in this context, since it does
> change the list length and so might crash unwary C extensions with
> some invariants.
True, the caller can shoot himself in the foot by bypassing your class
and calling list.pop(instance) instead of instance.pop(). That's a bad
thing, but probably unavoidable given Python's OO design.
However, it's also a fairly unusual thing to do: like calling "private"
double-underscore methods, anyone calling superclass.method(instance)
instead of instance.method() will know that they're doing something
unsupported and potentially dangerous.
Since we agree it's a bad thing, why do you want to copy it and create
another method which is even more dangerous, by design?
As I see it, Python already has a perfectly good solution for swapping
the contents of arbitrary mutable sequences, one which doesn't break
any invariants: a[:], b[:] = b[:], a[:]
What you really want is a fast way of initialising a list, given another
list. That was your use-case, after all. Swapping the contents is just
one particular implementation of that fast-initialise.
I believe that the correct place for this is inside a list constructor,
not as an external method which magically transports the internal data
from one list into another. I suggested adding extra functionality to
list.__new__, and Nick suggested a new constructor list.from_list().
Nick suggested making from_list destructive, but I don't see the
advantage of doing so. I think this is a probably a more productive
direction to take than a swap() method.
--
Steven D'Aprano
More information about the Python-ideas
mailing list