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

"Martin v. Löwis" martin at v.loewis.de
Mon Oct 26 06:53:30 CET 2009


> We were using sets to track the tips of a graph, and to compare whether
> one node was an ancestor of another one. We were caching that answer
> into frozensets, since that made them immutable. If
> 
> res = heads(node1, node2)
> if len(res) == 1:
>   # What is the 'obvious' way to get the node out?

What specifically is that that you want to do in this case?
IIUC, the possible result could be that either node1 is an ancestor
of node2, or vice versa.

So I would write that as

if len(res) == 1:
   if node1 in res:
     # action to take if node1 is the head
   else:
     # action to take if node2 is the head
else:
   # they are unrelated

In any case, this is a use case different from "work queue" (AFAICT),
so I'm unsure why you responded to my message where Florian and me were
talking about work queues.

> res.get() would be a fairly obvious way to do it. Enough that I would
> probably never have gone searching for any of the other answers. Though
> personally, I think I would call it "set.peek()", but the specific name
> doesn't really matter to me.

Somebody proposed to call it .any(); this I like best (except that one
might expect that any takes a predicate as the argument).

Regards,
Martin


More information about the Python-Dev mailing list