On Mon, Oct 25, 2021 at 08:39:19AM -0000, Jeremiah Vivian wrote:

> If I wanted to check if an *exact* object is in an iterable

A nice way to check for exact identity in an iterable is this:

    any(value is element for element in iterable)

That stops on the first match, and is pretty efficient. To reverse the 
check, "not in", use the obvious `not any(...)` as above.

"element is in iterable" reads nicely, but the difference between that 
and "element in iterable" is subtle and problematic.

Especially for English speakers, where "x in y" is strictly speaking 
grammatically incorrect:

    Wrong: if George in Europe, send him an email

    Right: if George is in Europe, send him an email


I'm surely not the only one who occassionally puts in an unwanted 
`is` into `in` tests. Fortunately that is a syntax error now.

Otherwise, it would silently do the wrong thing. And then the coder who 
accidentally inserts an unneeded `is` into the test will have to deal 
with weird implementation-dependent silent failures due to caching of 
small ints and strings:

    5 is in range(10)  # may succeed in CPython, but fail in Jython

    5000 is in range(4000, 6000)  # will probably fail everywhere

    5000 is in [4000, 5000, 6000]   # may succeed in CPython

    x = 5000
    x is in [4000, 5000, 6000]  # may or may not succeed

    int('5000') is in [4000, 5000, 6000]  # probably fail

    "a" is in "cat"  # probably succeed in CPython

    "cat" is in "caterpiller"  # definitely fail

    "CAT".lower() is in ['bat', 'cat', 'dog']  # possibly fail


So although the syntax reads nicely, it would be a bug magnet.



-- 
Steve
_______________________________________________
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/SRVKND2WMKRJBLZAK4ZZPAXEWECYNNSZ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to