[Python-Dev] Retrieve an arbitrary element from a set without removing it

Ben Finney ben+python at benfinney.id.au
Sat Oct 24 01:26:27 CEST 2009


Steven D'Aprano <steve at pearwood.info> writes:

> On Sat, 24 Oct 2009 06:04:12 am Terry Reedy wrote:
> > fwiw, I think the use case for this is sufficiently rare that it
> > does not need a separate method just for this purpose.
>
> And yet it keeps coming up, again and again... obviously people using
> sets in code think it has a use-case.

The desire for this may be obvious, but what seems to be lacking is One
Obvious Way to Do It.

I agree that ‘for x in foo_set: break’ is not an Obvious Way.

> The lack of get() in sets and frozensets is sounding more and more to
> me like the victory of purity over practicality.

What would be the input to ‘set.get’?

If it's the value, that makes it rather non-obvious; if I already know
about ‘dict.get’ which takes the key, I'm not going to be thinking about
the ‘get’ method if I don't have a key to feed it. Once I learn it, I'm
going to forget it easily, because it's inconsistent with ‘dict.get’. So
I don't think that meets the “obvious way” criterion.

By analogy with ‘list.pop’, the method that takes the “top” item off the
“stack”, I would expect to see ‘list.peek’ and ‘set.peek’, to see the
item without altering the container.

-- 
 \        “Odious ideas are not entitled to hide from criticism behind |
  `\          the human shield of their believers' feelings.” —Richard |
_o__)                                                         Stallman |
Ben Finney



More information about the Python-Dev mailing list