[Python-bugs-list] [ python-Bugs-639806 ] Optional argument for dict.pop() method
noreply@sourceforge.net
noreply@sourceforge.net
Sun, 17 Nov 2002 15:00:34 -0800
Bugs item #639806, was opened at 2002-11-17 23:00
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=639806&group_id=5470
Category: Python Interpreter Core
Group: Python 2.3
Status: Open
Resolution: None
Priority: 5
Submitted By: Fernando Pérez (fer_perez)
Assigned to: Nobody/Anonymous (nobody)
Summary: Optional argument for dict.pop() method
Initial Comment:
I think the new dict.pop() method should support an optional argument for its return value when a key is not found.
The current behavior (raising KeyError always) IMHO violates the principle of least surprise, since the very similar get() method _does_ support an optional return value. I am filing this as a bug on suggestion by Neil Schemenauer in c.l.py.
Here is a python proof of concept which I am using , implemented as a function. If this were accepted, similar behavior would need to be coded in the pop() method itself, which I suppose is part of the C core.
#----------------------------------------------------------------------------
class NotGiven: pass
def popkey(dct,key,default=NotGiven):
"""Return dct[key] and delete dct[key]. dct is modified in-place.
If default is given, return it if dct[key] doesn't exist, otherwise raise
KeyError. """
try:
val = dct[key]
except KeyError:
if default is NotGiven:
raise
else:
return default
else:
del dct[key]
return val
#----------------------------------------------------------------------------
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=639806&group_id=5470