[Python-ideas] Add single() to itertools
steve at pearwood.info
Mon Oct 30 21:09:09 EDT 2017
On Tue, Oct 31, 2017 at 07:51:02AM +1100, Cameron Simpson wrote:
> return the(nodes)
> It's this kind of thing that expresses my intent better than the:
> node, = nodes
> return node
If the intent is to indicate that there is only one node, then
"the(nodes)" fails completely. "The" can refer to plurals as easily as
"Wash the dirty clothes."
(Later) "Why did you only wash one sock?"
The simplest implementation of this "single()" function I can think of
result, = iterable
That raises ValueError if iterable has too few or too many items, which
I believe is the right exception to use. Conceptually, there's no
indexing involved, so IndexError would be the wrong exception to use.
We're expecting a compound value (an iterable) with exactly one item. If
there's not exactly one item, that's a ValueError.
More information about the Python-ideas