[Python-ideas] data structures should have an .any() method

Scott David Daniels Scott.Daniels at Acm.Org
Tue Sep 8 23:05:05 CEST 2009

Steven D'Aprano wrote:
> On Sun, 6 Sep 2009 03:51:43 pm Greg Ewing wrote:
>> Nick Coghlan wrote:
>>> That said, I'm -0 on the idea overall. If someone actually needs
>>> it, it isn't particularly hard for them to write their own getany()
>>> function.
>> There's a situation where the need to do this kind of
>> thing actually arises fairly frequently -- retrieving
>> things from a relational database. Often you're
>> expecting exactly one result from a query, but the
>> API always gives you a sequence, which you then have
>> to get the first item from. Doing that over and
>> over again gets rather tedious.
> If you're expecting "exactly one result", then surely it should be an 
> error to receive more than one result? Rather than ask for "any" result 
> and ignoring any unexpected extra items, I think it would be better to 
> have a helper function that verifies you have got exactly one result.

Well, some queries return results without duplicate elimination, even
though they are defined to return sets.  If you really want to limit
things in databases queries, the "LIMIT 1" clause is your friend, as
the query optimizer knows it can stop as soon as its found something.
Of course I don't know which query optimizers around now _use_ that
knowledge to pick a query plan, but that leaves the info there if
the next rev becomes limit-capable.

Often when I just want to pick a single value from a column I use MIN
or MAX (and fairly often when I need two distinct values I use both MIN 
and MAX).

One trick to seeing a column is exactly a singleton is:
     SELECT MIN(something)
     FROM ...
     WHERE MIN(something) = MAX(something)

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-ideas mailing list