Tuples and immutability

Chris Angelico rosuav at gmail.com
Sun Mar 9 21:06:37 CET 2014


On Mon, Mar 10, 2014 at 6:57 AM, Joshua Landau <joshua at landau.ws> wrote:
> I would probably implement it closer to home. Inside
> tuple.__getitem__, there would be something like
>
>     if context_is_augmented_assignment():
>         raise TypeError(message+warning)
>     else:
>         raise TypeError(message)
>
> which would have much lower technical costs. It does depend on how
> costly "context_is_augmented_assignment" is, though. A speed argument
> is totally valid, but I'd hope it's possible to work around.

Yeah, I'm not sure there's an easy way to tell the tuple that it's an
augmented assignment. You might be able to look at the backtrace, but
that's tricky.

In theory, you could catch TypeError after any augmented assignment,
and check several things:
1) The target object does not have __setitem__
2) The object being manipulated does have __iadd__ (or corresponding for others)
3) The error is that item assignment is not possible

and if all three are the case, then add a tag to the message. But this
is best done by catching the exception. Otherwise you'd be limiting
this to tuples and lists; not to mention that this is really only an
issue of error reporting, and correct code shouldn't be tripping this
at all. So put a check like that at the place where you display the
error, if you can. The AST transform that I described would also work.

But I really think it's not worth the effort. If you get this error,
understand that it may have consequences.

ChrisA



More information about the Python-list mailing list