[Python-ideas] get method for sets?

Steven D'Aprano steve at pearwood.info
Wed May 16 18:28:22 CEST 2012


Mike Meyer wrote:

> I didn't ask for a get that would always return the same element.

It seems to me that you haven't exactly been clear about what you want this 
get() method to actually do. In an earlier email, you said:

[quote]
My requirements are "I need an element from the set". The behavior of
repeated calls is immaterial.
[end quote]

So a get() which always returns the same element fits your requirements, *as 
stated*. If you have other requirements, you haven't been forthcoming with them.

I've never come across a set implementation which includes something like your 
get() method. Does anyone know any language whose set implementation has this 
functionality? Wikipedia currently suggests it isn't a natural method of sets:

     Unlike most other collection types, rather than retrieving a
     specific element from a set, one typically tests a value for
     membership in a set.

http://en.wikipedia.org/wiki/Set_%28computer_science%29

For all you say it is a common request, I don't think it's a well-thought-out 
request. It's one thing to ask "give me any element without modifying the 
set", but what does that mean exactly? Which element should it return? "Any 
element, so long as it isn't always the same element twice in a row" perhaps? 
Would flip-flopping between the first and second elements meet your requirements?

The example you give below:


> For instance, I happen to know I have a set of ElementTree elements
> that all have the same tag. I want to check the tag.
> 
> One of the test cases starts by checking to see if the set is a
> singleton. Do you really propose something like:

is too much of a special case to really matter. A set with one item avoids all 
the hard questions, since there is only one item which could be picked. It's 
the sets with two or more items that are hard. A general case get/pick method 
has to deal with the hard cases, not just the easy one-element cases.


[...]
> All of these require creating an intermediate object for the sole
> purpose of getting an item out of the container without destroying the
> container. This leads the reader to wonder why it was created, 

You've just explained why it was created -- to get an item out of the set 
without destroying it. Why is this a problem? We do something similar 
frequently, often abstracted away inside a helper function:


first = list(iterable)[0]
num_digits = len(str(some_integer))

etc.




-- 
Steven




More information about the Python-ideas mailing list