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

Steven D'Aprano steve at pearwood.info
Sat Sep 5 07:17:05 CEST 2009

On Fri, 4 Sep 2009 08:03:21 pm Nick Coghlan wrote:
> Stefan Behnel wrote:
> > It would therefore be nice to have a common ".any()" method on data
> > structures that would just read an arbitrary item from a container.
> I'd advise against bare name "any" for this, since we already have
> the any() builtin with a completely different meaning. "getany" would
> probably be OK though.
> I'd also advise against using a method for this, since there is a
> reasonable default implementation that can be employed:
> def getany(container)
>   if container:
>     if isinstance(container, collections.Sequence):
>       return container[0]
>     else:
>       for x in container:
>         return x
>   raise ValueError("No items in container")
> Finally, I'd suggest that any such function would belong in the
> collections module rather than being made a builtin.

Given the above implementation, repeated calls to getany(sequence) will 
return the same item each time. Is that what people will expect by a 
function that claims to return "any" element of a collection? I suspect 
that users will be evenly divided into those who say Yes, those who say 
No, and those who say "It depends on what I'm trying to do".

Should it return an arbitrary item, or a random item? Is "the first 
item" arbitrary enough? It should be for dicts, which are unordered, 
but may not be for lists.

I think the answers to these questions are too application-specific for 
any solution or solutions to go into the standard library. It probably 
belongs in the cookbook as a handful of related recipes.

Steven D'Aprano

More information about the Python-ideas mailing list