[Python-Dev] Retrieve an arbitrary element from a set withoutremoving it
chris at subtlety.com
Sat Oct 31 02:43:31 CET 2009
On Fri, Oct 30, 2009 at 8:29 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> > Iterating over an iterable is
>> > what iterators are for.
> set.get(), or set.pick() as Wikipedia calls it, isn't for iterating over
> sets. It is for getting an arbitrary element from the set.
> If the requirement that get/pick() cycles through the sets elements is
> the killer objection to this proposal, I'd be willing to drop it. I
> thought that was part of the OP's request, but apparently it isn't. I
> would argue that it's hardly "arbitrary" if you get the same element
> every time you call the method, but if others are happy with that
> behaviour, I'm not going to stand in the way.
It's arbitrary in the sense that the API doesn't make any
assurances which item the caller will get, not that it's arbitrary for
any particular * implementation*.
> The purpose is to
> return an arbitrary item each time it is called. If two threads get the
> same element, that's not a problem; if one thread misses an element
> because another thread grabbed it first, that's not a problem either.
> If people prefer a random element instead, I have no problem with
> that -- personally I think that's overkill, but maybe that's just me.
I also think returning a random one is overkill, in the base set.
And I'd have the base implementation do the simplest thing possible:
return a fixed element (either the first returned when iterated over,
or the last stored, or whatever's easiest based on the internals).
For me, leaving the choice of *which* element to return on each call
is a feature. It allows subclasses to change the behavior to support
other use cases, like a random or round-robin behavior.
More information about the Python-Dev