[Python-ideas] Adding "+" and "+=" operators to dict
Andrew Barnert
abarnert at yahoo.com
Sat Feb 14 03:53:17 CET 2015
On Feb 13, 2015, at 18:19, Steven D'Aprano <steve at pearwood.info> wrote:
> The narrower lesson is that I am cautious about using operators when a
> method or function can do. Saving a few keystrokes is not sufficient.
> Bringing it back to dicts:
>
> settings.printer_config.update(global_settings, user_settings)
>
> is obvious and easy and will not fail if blob is a named tuple or
> printer_config is a read-only property (for example), while:
>
> settings.printer_config += global_settings + user_settings
>
> may succeed and yet still raise an exception.
I think another way to look at this is that += is an assignment, while update isn't. In this case, you don't really want to assign anything to settings.printer_config, you want to modify what's there. So a method call like update makes more sense, even if it's a bit more verbose. If you always think things through like that, you'll never run into the "tuple wart".
Of course your point about C is well-taken: assignment in C (and even more so in descendants like C++) is a very different thing from assignment in Python, and given how many Python developers come from a C-derived language, it's not surprising that people have inappropriate intuitions about when += is and isn't appropriate, and occasionally run into this problem.
On the third hand, the problem doesn't come up very often in practice--that's why so many people don't run into it until they're already pretty experienced (and are therefore even more surprised), which implies that maybe it's not that important to worry about in the first place...
More information about the Python-ideas
mailing list