[Tutor] Standard way to append to a list? ['+=' is in-place
Wed Apr 16 21:21:02 2003
On Wed, 16 Apr 2003, Danny Yoo wrote:
> Wait a minute... I can't seem to prove this by overriding the extend()
> >>> class mylist(list):
> ... def extend(self, other):
> ... print "I'm extend()!"
> ... list.extend(self, other)
> >>> l = mylist([1, 2, 3])
> >>> l += 
> >>> l
> [1, 2, 3, 4]
> >>> l.extend()
> I'm extend()!
> Weird! I'm using Python 2.2.1 here; can anyone confirm if this is
> happening with Python 2.2.2 or 2.3alpha? Does this look like a bug to
> anyone else? ... Checking SourceForge... nope, I don't see anything
> about this.
Hmmm... I played around with this a little more. It does work if we
override __iadd__ (in-place adding):
>>> class mylist(list):
... def __iadd__(self, other):
... print "I'm __iadd__()"
... return list.__iadd__(self, other)
>>> l = mylist([1, 2, 3])
>>> l += 
[1, 2, 3, 4]
__iadd__ is briefly mentioned in the Python Standard Reference here:
So the system is not totally broken. What appears to be the issue is that
__iadd__() for lists is hardcoded to use the primitive C function
'listextend_internal()'. I feel, though, that a list subclass should
really check to see if the extend() function has been redefined when it's
doing a '+=' operation, to maintain polymorphic behavior. Dunno how that
will affect performance, though.
In any case, I'll send a bug report to SourceForge later tonight and see
how the implementors feel about this... *grin*