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

Nick Coghlan ncoghlan at gmail.com
Fri Jun 26 11:06:13 CEST 2009

Steven D'Aprano wrote:
> 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. 

I think Kristján's point was that list.pop() and friends don't perform a
PyList_CheckExact on themselves before following their fast path
implementation so they can bypass custom get/set/del methods in subclasses.

So subclasses that override __delitem__ to do some additional
bookkeeping without overriding pop() could get a nasty surprise when
someone calls pop() on them. This would be similar to the oddities that
can happen when you override dict.__setitem__ without overriding

Then again, maybe we just need to document this behaviour as a trap of
subclassing the mutable builtins: make sure to override *all* the
mutating methods in subclasses, not just the special methods.


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

More information about the Python-ideas mailing list