When I need something like this, I usually rop a line on the module namespace that goes like: first = lambda x: next(iter(x)) On 30 October 2017 at 23:09, Steven D'Aprano <steve@pearwood.info> wrote:
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
idiom.
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 singular:
"Wash the dirty clothes." (Later) "Why did you only wash one sock?"
The simplest implementation of this "single()" function I can think of would be:
def single(iterable): result, = iterable return result
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.
-- Steve _______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/