On Friday, June 26, 2020, at 04:54 -0500, Steven D'Aprano wrote:

On Thu, Jun 25, 2020 at 05:27:16PM +0300, Ben Avrahami wrote:
Hey all,
Often I've found this kind of code:

seen = set()
for i in iterable:
  if i in seen:
    ...  # do something in case of duplicates
  else:
    seen.add(i)
    ... # do something in case of first visit

This kind of code appears whenever one needs to check for duplicates in case of a user-submitted iterable, or when we loop over a recursive iteration that may involve cycles (graph search or the like). This code could be improved if one could ensure an item is in the set, and get
whether it was there before in one operation.

Whereas this:

    # Check for duplicates.
    add element to the collection
    was it already there before you just added it?

is a weird way to think about the problem.

    already_there = seen.add(element)
    if already_there:
        # handle the duplicate case

Who thinks like that? *wink*

Anyone who practices EAFP rather than LBYL? Or is that why you're winking?

But either way, you also have to decide whether the `add` (or the new method) should *unconditionally* insert the element, or only do so if it wasn't present. This makes a big difference:

    seen = {2}
    already_there = seen.add(2.0)

At this point, is `seen` the set {2} or {2.0}? Justify why one answer is the best answer.

The actual best answer is left as an exercise for the interested reader, but whatever it is, it's justified by backwards compatibility, the existing definition of "present," and the principle of least surprise:

   Python 3.8.3 (default, May 17 2020, 18:15:42)
   [GCC 10.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
   >>> seen = {2}
   >>> 2.0 in seen
   True
   >>> seen.add(2.0)
   >>> seen
   {2}

Unless the new method is called set.add_with_different_semantics. ;-)
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/X7MDBK5BGA4G3W4H7UNGNGJSSWI3ZT7G/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to