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

Kristján Valur Jónsson kristjan at ccpgames.com
Fri Jun 26 00:37:36 CEST 2009

Since this is Python-ideas, I'm going to persist a bit with my argumentation, even though I concede defeat :)
I'm going for a generic SwapLists(a,b) function in C, since my list subclass isn't written in C.

> -----Original Message-----
> From: Raymond Hettinger [mailto:python at rcn.com]
> Sent: 25. júní 2009 21:58
> The sort() method is closer in spirit.  It does mutate the list in-
> place, so any list subclasses must either disable sort() by
> overriding it or it needs to limit its invariants to ones that aren't
> affected by the mutation.  This is unfortunate because it
> places a burden on every class that inherits from list.  So even though
> you've found a precedent, I don't think it is something that
> we want to have more of.

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.

> Also, the situation for swap() is made more difficult because there are
> two parties (the swapper and the swappee).  With sort(), a
> subclass is giving permission for mutation by not overriding the sort
> method.  With swap(), the swappee has no say in the matter.
> There is no way for a swappee's class to declare that its invariants do
> not support swapping.  The situation is even more acute when
> the swappee is a C extension inheriting from list -- violating its
> invariants may crash the interpreter.

I do have a suggested solution for that:  Require that the swapee is not a list subclass, by using PyList_CheckExact().  That does make it safer at the cost of narrowing the application domain.

Anyway, I'm going to mark the issue as "rejected" and get on with life.  Thank you Raymond for your insightful comments.


More information about the Python-ideas mailing list