popkey() method for dictionaries?
Fernando Pérez
fperez528 at yahoo.com
Mon Nov 18 14:25:15 EST 2002
John Hunter wrote:
>>>>>> "Fernando" == Fernando Pérez <fperez528 at yahoo.com> writes:
>
> Fernando> Sure. First, on principle: the exception option is still
> Fernando> there, if no default is provided. What giving a default
> Fernando> buys you is not having to trap the exception
> Fernando> yourself. If you want a missing key to generate an
> Fernando> exception, simply don't give a default and that's
> Fernando> it.
>
> But then you break the symmetry with get, which provides None as a
> default if no default is provided. Aren't you now back in danger of
> violating the principle of least surprise?
Mmmh. I hadn't used get without default in a long time, and I'd forgotten its
not-found return was a None instead of an exception. I would argue _that_
violates the 'explicit is better than implicit' rule of python, but it's a
bit late to change that one :)
In general, since these are all wrappers around dict[key] access operations,
and at the most basic level such an access to a non-existent key _will_
trigger an exception, I'd argue that the default behavior of all these
functions (get, pop, popitem) should be to raise an exception. In this way
they would most naturally mimic the underlying semantics, without magic
behaviors. On the other hand, I think it is _useful_ syntactic convenience to
have a way of explicitly overriding the exception triggering, for the reasons
Alex Martelli and I argued elsewhere in this tread.
Unfortunately these functions (get/pop/popitem) have already been written with
(it seeems to me) inconsistent interfaces, and we'll just get used to keeping
track of who does what with post-it notes.
Cheers,
f.
More information about the Python-list
mailing list