On Fri, Jun 26, 2020 at 06:16:05AM -0500, Dan Sommers wrote: > > 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?
That doesn't come naturally, and in single-threaded code it's also unnecessary. By the way, since there's no try...except involved and no need to catch an exception, it's not EAFP. > >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: The documentation doesn't guarantee one behaviour or another: https://docs.python.org/3/library/stdtypes.html#frozenset.add > 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} Well I'm completely surprised, because I expected `add` to, you know, actually add the element replacing the one that was already there! Seriously, I genuinely thought that the existing behaviour was the opposite and that `add` unconditionally added the element. "Last seen wins". If I was designing sets, that's probably how I would design it. After all, it's called *add*, not *add if not already there*. I was so sure that this was the current behaviour that I didn't bother to check it before posting, which is rare for me. So I think this counts as the principle of maximal surprise :-) Should the flag be "element was already present and nothing was added" or "element was not there, so something was added"? -- Steven _______________________________________________ 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/3Z5KH7FCAUK6WLXOBLMBSKC54BMZ2H57/ Code of Conduct: http://python.org/psf/codeofconduct/