Issue 25016: defaultdict's pop gives a KeyError (original) (raw)
Issue25016
Created on 2015-09-07 06:27 by rob.anyone, last changed 2022-04-11 14:58 by admin. This issue is now closed.
Messages (3) | ||
---|---|---|
msg250080 - (view) | Author: Chase Albert (rob.anyone) | Date: 2015-09-07 06:27 |
`defaultdict(list).pop(1)` raises a KeyError, this is not what I expected (I expected an empty list). | ||
msg250081 - (view) | Author: Martin Panter (martin.panter) * ![]() |
Date: 2015-09-07 06:37 |
I think this is by design. Under <https://docs.python.org/3/library/collections.html#collections.defaultdict.__missing__> it says “__missing__() is _not_ called for any operations besides __getitem__().” What gave you the impression that pop() should return a default value? | ||
msg250140 - (view) | Author: R. David Murray (r.david.murray) * ![]() |
Date: 2015-09-07 23:59 |
It would not be sensible for pop to return the default value, since the point of pop is to *remove* a key from the dictionary (while returning the existing value), whereas the point defaultdict is to *add* key to the dictionary with the default value if you retrieve a non-existent key. As Martin said, an important aspect of defaultdict is that *only* getattr has this default behavior; things like 'in' still work like a regular dictionary with a defaultdict. |
History | |||
---|---|---|---|
Date | User | Action | Args |
2022-04-11 14:58:20 | admin | set | github: 69204 |
2015-09-07 23:59:46 | r.david.murray | set | status: open -> closednosy: + r.david.murraymessages: + resolution: not a bugstage: resolved |
2015-09-07 06:37:47 | martin.panter | set | nosy: + martin.pantermessages: + |
2015-09-07 06:27:26 | rob.anyone | create |