[Python-ideas] get method for sets?

Bruce Leban bruce at leapyear.org
Wed May 16 10:08:09 CEST 2012


On Wed, May 16, 2012 at 12:40 AM, Mike Meyer <mwm at mired.org> wrote:

> On Wed, 16 May 2012 00:02:31 -0700
> Bruce Leban <bruce at leapyear.org> wrote:
>


> > Here's one definition of get:
> > def get_from_set1(s):
> >     """Return an arbitrary member of a set."""
> >     return min(s, key=hash)
>
> >From poking around, at least at one time the fastest implementation
> was the very confusing:
>
> def get_from_set(s):
>    for x in s:
>        return x
>

I didn't claim it was fast. I actually wrote that version instead of the
in/return version for a very specific reason: it always returns the same
element. (The for/in/return version might return the same element every
time too but it's not guaranteed.)

> How is this useful?
>
> Basically, anytime you want to examine an arbitrary element of a set,
> and would use pop, except you need to preserve the set for future
> use. In my case, I'm running a series of tests on the set, and some
> tests need an element.
>
> That's bordering on tautological. It's useful anytime you need it. I don't
think your test is very good if it uses the get I wrote above. Your test
will only operate on one element of the set and it's easy to write
functions which succeed for some elements of the set and fail for others.
I'd like to see an actual test that you think needs this that would not be
improved by iterating over the list.



> Again, looking for a reason for this not existing turned up other
> cases where people were wondering how to do this.
>

Things are added to APIs and libraries because they are useful, not because
people wonder why they aren't there. set.get as you propose is not
sufficiently analogous to dict.get or list.__getitem__.

--- Bruce
Follow me: http://www.twitter.com/Vroo http://www.vroospeak.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120516/c10455b4/attachment.html>


More information about the Python-ideas mailing list