[Python-ideas] OrderedDict.peekitem()

Chris Angelico rosuav at gmail.com
Tue Jul 7 16:59:54 CEST 2015


On Wed, Jul 8, 2015 at 12:58 AM, Chris Angelico <rosuav at gmail.com> wrote:
> 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

Doh. Next time, Chris, look first, *then* post.

https://github.com/erikrose/more-itertools/blob/master/more_itertools/more.py#L40

ChrisA


More information about the Python-ideas mailing list