On Fri, Jul 31, 2020 at 08:08:58PM -0700, Guido van Rossum wrote:
> > The other simple solution is `next(iter(mydict.items()))`.
> >
>
> That one always makes me uncomfortable, because the StopIteration it raises
> when the dict is empty might be misinterpreted. Basically I never want to
> call next() unless there's a try...except StopIteration: around it, and
> that makes this a lot less simple.
Acknowledged. But there are ways to solve that which perhaps aren't as
well known as they should be.
* Use a default: `next(iter(mydict.items()), MISSING)`
* Use a helper to convert StopIteration to something else.
Some years ago, someone (I think it was Nick Coghlan?) proposed a
standard solution for this issue, a context manager + decorator function
that guarded against a specific exception. Nothing much came of it, but
I did experiment with the idea, and got something which you could use
like this:
with exception_guard(StopIteration):
first = next(iter(mydict.items()))
or like this:
safenext = exception_guard(StopIteration)(next)
first = safenext(iter(mydict.items()))
I think that would be a good tool for the functools library, but I
acknowledge that even if standard, it would be a little too obscure for
most people thinking "I need the first key from this dict".
--
Steven
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/7HUGB5JJIJS6JCQBU4GM4X7BPYYNPRC3/
Code of Conduct: http://python.org/psf/codeofconduct/