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

Terry Reedy tjreedy at udel.edu
Sat Oct 24 21:37:27 CEST 2009

Alexander Belopolsky wrote:
> On Fri, Oct 23, 2009 at 6:46 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> 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.
> This reminds me a debate I had with Martin several years ago:
> http://bugs.python.org/issue1507011
> Here is the essence:
> AB> I disagree with Martin. I think interning is a set
> AB> operation and it is unfortunate that set API does not
> AB> support it directly.
> ML> I disagree with Alexander's last remark in several respects:
> ML> set is indeed a container, and there is a way to get the
> ML> elements back (namely, by enumerating them, or picking an
> ML> arbitrary element for removal). There is no operation to check,
> ML> on insertion of E, what the the prior element equal to E was
> ML> (if any); there is only a check to determine whether E is in the
> ML> set. The operation "give me the member equal but not identical
> ML> to E" is conceptually a lookup operation; the mathematical set
> ML> construct has no such operation, and the Python set models
> ML> it closely. IOW, set is *not* a dict with key==value.
> To me, however, a set seems to be a container that is a specialization
> of a dict with values and keys being the same.

As I explained in response to Steven, set()s *implicitly* map of 
abstract, non-object equivalence classes to a concrete, representative 
object/member of that class.

 >  In this model, a
> get() method, or even a __getitem__ with s[k] is k, is only natural.

No, if key and value were the same thing, the get method would be 
nonesense, as Guido said. But since they are not, since the implict key 
is an abstract class, retrieving the representative, perhaps canonical 
object given *any* member *is* natural. Being able to do so is also a 
standard practice in mathematics.

Terry Jan Reedy

More information about the Python-Dev mailing list