[Python-ideas] Add single() to itertools
Cameron Simpson
cs at cskk.id.au
Mon Oct 30 16:51:02 EDT 2017
On 30Oct2017 07:32, Guido van Rossum <guido at python.org> wrote:
>This is a key example of a case where code speaks. Can you write an
>implementation of how you would want single() to work in Python code?
Myself, I'm not advocating for putting such a thing in itertools. However, I do
have an equivalent utility function of my own that makes for more readable
code, named "the".
It sees far less use than I'd imagined it would, but it does read nicely to my
eye when used. I have a few select-something from data where there _can_ be
multiple hits i.e. the data format/structure support multiple matching results,
but the caller's use case requires just one hit or failure.
So I have some fuzzy-db-lookup functions which end with:
return the(rows)
or include:
row = the(rows)
and some HTML find-this-DOM-node code which ends with:
return the(nodes)
It's this kind of thing that expresses my intent better than the:
node, = nodes
return node
idiom. And as remarked, you can embed the() in an expression.
I don't think it ranks in "belongs in the stdlib". I do keep it about in a
module for ready use though. If nothing else, it raises IndexErrors with
distinct text for 0 and >1 failure.
Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
More information about the Python-ideas
mailing list