This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: MutableMapping ".setdefault()" to return default value via __getitem__
Type: enhancement Stage: resolved
Components: Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: guijarro, gvanrossum, rhettinger
Priority: normal Keywords:

Created on 2020-08-27 10:28 by guijarro, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg375984 - (view) Author: Matias G (guijarro) Date: 2020-08-27 10:28
Hi,

This is more a question/proposal than a real issue. I apologize in
advance if this has already been debated or if it is not relevant.

I noticed `setdefault` method of mutable mapping objects is returning
the default value as passed in the call, when applicable, without
passing through `__getitem__`.

I think it would be more "symmetric" if it would return the default
value set by `__setitem__` via `__getitem__`. This would handle the
case of a custom MutableMapping defining a custom behaviour of
`__setitem__` and `__getitem__`.

Of course, in my case finally I overloaded `setdefault` to do this,
but it might be worth in general, at least for the MutableMapping
class.

Thanks,
Matias.
msg376015 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2020-08-28 02:32
The current code makes sense to me and also mirrors the actual implementation of setdefault() for regular dictionaries. 

While I can see what you're trying do, it is a feature that __getitem__() is not called.  And for regular dicts, that is the only way to make it an atomic operation.

In any case, the proposal would be a behavior change that breaks code — users are likely and justifiably relying on the actual default value being returned rather than a possibly new value computed by the __getitem__() method.

There is also an efficiency concern.  Changing the behavior implies that missing keys would trigger one initial search, then a store for the default, and then another subsequent lookup.  Speaking only for myself, I know that I would never want that by default.  If required, I would prefer to override setdefault() and explicitly spell-out the new behavior.
msg376016 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2020-08-28 03:27
I'm with Raymond. Closing.
History
Date User Action Args
2022-04-11 14:59:35adminsetgithub: 85813
2020-08-28 03:27:58gvanrossumsetstatus: open -> closed
resolution: not a bug
messages: + msg376016

stage: resolved
2020-08-28 02:32:08rhettingersetnosy: + gvanrossum
messages: + msg376015
2020-08-27 11:54:42xtreaksetnosy: + rhettinger
2020-08-27 10:28:20guijarrocreate