On Sat, Jun 16, 2018 at 9:09 PM, Steven D'Aprano <st...@pearwood.info> wrote:
> On Sat, Jun 16, 2018 at 01:06:45PM +1200, Greg Ewing wrote:
>> Michael Selik wrote:
>> >The += operator was meant as an alias for ``x = x + 1``. The
>> >fact that it mutates a list is somewhat of a surprise.
>>
>> That's very much a matter of opinion. For every person who
>> thinks this is a surprise, you can find another that thinks
>> it's obvious that += should mutate a list, and is surprised
>> by the fact that it works on immutable types at all.
>
> Given the ubiquity of += in C, where it works on numbers but not lists,
> and the general difficulty many people have in dealing with the
> difference between assignment and mutation, I think the ratio would be
> closer to 20:1 than 1:1.

The nearest you'd get to "adding to a list/array" in C would be adding
to a pointer. But I don't see people writing code like this in Python:

>>> x = [10, 20, 30, 40]
>>> x += 1
>>> assert x == [20, 30, 40]

:)

> But regardless, I'm pretty sure that nobody expects this:
>
>
> py> t = ([], None)
> py> t[0] += [1]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
> py> print(t)
> ([1], None)
>

Agreed, although I can't remember this ever coming up outside of
interactive work. When you do something at the interactive prompt, you
can kinda feel that it should "rollback" on exception, and yet some
part of it has happened. But in most scripts, that TypeError is going
to pull you all the way out of the scope where 't' exists -
frequently, it'll just straight-up terminate the script - so you won't
often see this.

ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to