Message13329
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
#----------------------------------------------------------------------------
|
|
Date |
User |
Action |
Args |
2007-08-23 14:08:53 | admin | link | issue639806 messages |
2007-08-23 14:08:53 | admin | create | |
|