[Python-ideas] OrderedDict.peekitem()

Chris Angelico rosuav at gmail.com
Tue Jul 7 16:58:43 CEST 2015


On Wed, Jul 8, 2015 at 12:35 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> If the OrderedDict is empty both of the above will raise StopIteration. This
> can have unintended consequences if the OrderedDict is called from another
> iterator/generator etc. So it should probably be:
>
> def first(od):
>     try:
>         return next(iter(od))
>     except StopIteration:
>         raise KeyError

Agreed, though it's worth noting that as of Python 3.5, generators can
be made not-vulnerable to this problem (and as of 3.7ish, they
automatically will be protected). See PEP 479 for details. But yes,
turning that into KeyError is the right thing to do, and is exactly
why something like this wants to be a published recipe rather than
simply dismissed as "see how easy it is?".

Does it belong in a collection like moreitertools?

ChrisA


More information about the Python-ideas mailing list