popkey() method for dictionaries?

Fernando Pérez fperez528 at yahoo.com
Sun Nov 17 18:05:07 EST 2002


Neil Schemenauer wrote:

> It seems like an oversight.  Here's the original patch:
> 
>   http://sf.net/tracker/?group_id=5470&atid=305470&func=detail&aid=539949
> 
> Feel free to file a bug.  Cheers,

Just filed:

[ 639806 ] Optional argument for dict.pop() method

at:
https://sourceforge.net/tracker/index.php?func=detail&aid=639806&group_id=5470&atid=105470

Sorry but I just saw that my proof-of-concept code in python got squashed by 
SF. I didn't know that SF removed all leading whitespace, hence destroying 
indentation. Here it is again for reference:

#----------------------------------------------------------------------------
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
#----------------------------------------------------------------------------

Cheers,

f.



More information about the Python-list mailing list