On Mon, Sep 8, 2014 at 10:30 PM, Stephen R. van den Berg <s...@cuci.nl> wrote:
> Let the record show though that I consider it to be a rather messy way
> to handle this :-).

I've worked with Python's way of doing things, and it has its own
issues. This kind of thing comes up periodically on python-list:

>>> t = ("Foo", [1,2], "Bar")
>>> t[1] += [3]
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    t[1] += [3]
TypeError: 'tuple' object does not support item assignment
>>> t
('Foo', [1, 2, 3], 'Bar')

In Python, "x += y" becomes "x = x.__iadd__(y)", which means two things:

1) The object is asked to do an in-place addition with the new contents
2) Whatever is returned is stored back where x was.

The tuple rejects the second half of that (tuples are immutable, so
you can't assign to their members), but the first half has already
happened, and this causes some confusion.

With Pike's semantics, "t[1] += whatever" becomes "t[1] = t[1] +
whatever", which won't change t[1] at all if the assignment fails.
There's a much stronger incentive to write explicit methods to do the
appending (in Python's case, lists have a .extend() method that's
better suited to this, but there's a temptation to use += anyway),
because it's guaranteed to be more efficient.

Personally, I think use of += for anything other than pure
optimization is a dangerous idea - the expected semantics aren't as
obvious as you might think. It's easy with immutables like strings and
integers (this is true in both Python and Pike, btw), but for
mutables, it's cleaner to work with methods.

ChrisA

Reply via email to