[Python-bugs-list] [ python-Bugs-639806 ] Optional argument for dict.pop() method

noreply@sourceforge.net noreply@sourceforge.net
Mon, 18 Nov 2002 00:02:29 -0800


Bugs item #639806, was opened at 2002-11-17 18: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
#----------------------------------------------------------------------------


----------------------------------------------------------------------

>Comment By: Raymond Hettinger (rhettinger)
Date: 2002-11-18 03:02

Message:
Logged In: YES 
user_id=80475

dict.pop(k) parallels list.remove(elem), dict.popitem(), and 
list.pop([i]) which all raise exceptions instead of returning 
a default.

Do you have compelling use cases?

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=639806&group_id=5470