[Python-ideas] get method for sets?
Steven D'Aprano
steve at pearwood.info
Wed May 16 08:58:43 CEST 2012
On Wed, May 16, 2012 at 02:32:15AM -0400, Mike Meyer wrote:
> Is there some reason that there isn't a straightforward way to get an
> element from a set without removing it? Everything I find either
> requires multiple statements or converting the set to another data
> type.
>
> It seems that some kind of get method would be useful. The argument
> that "getting an arbitrary element from a set isn't useful" is refuted
> by 1) the existence of the pop method, which does just that,
pop returns an arbitrary element, and removes it. That's a very
different operation to "get this element from the set".
The problem is, if there was a set.get(x) method, you have to pass x as
argument, and it returns, what? x. So what's the point? You already have
the return value before you call the function.
def get(s, x):
"""Return element x from set s."""
if x in s: return x
raise KeyError('not found')
As I see it, this is only remotely useful if:
- you care about identity, e.g. caching/interning
- you care about types, e.g. get(s, 42) may return 42.0 as the element
of the set instead.
In either case, a dict is the more obvious data structure to use.
def intern(d, x):
"""Intern element x in dict d, and return the interned version."""
return d.setdefault(x, x)
But with sets? Seems pretty pointless to me. I can't help but feel that
set.get() is a poorly thought out operation, much requested but rarely
useful.
> and 2)
> the fact that I (and a number of other people) have run into such a
> need.
>
> My search for such a reason kept finding people asking how
> to get an element instead. Of course, my key words (set and get) are
> heavily overloaded.
What's your use-case?
--
Steven
More information about the Python-ideas
mailing list