On Mon, Oct 25, 2021 at 8:35 PM Steven D'Aprano <st...@pearwood.info> wrote: > > 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. >
It's worth noting that "in" is defined by the container. Object identity and equality aren't actually part of the definition. A lot of containers will behave as the OP describes, but strings, notably, do not - if you iterate over "caterpillar", you will never see "cat", yet it is most definitely contained. An "is in" operator is half way between being defined by the operator and defined by the container. This won't work for all containers. If you need that kind of thing a lot, it's not that hard to define a search object accordingly: class Is: def __init__(self, obj): self.obj = obj def __eq__(self, other): return self.obj is other >>> Is(x) in container But this is a code smell. ChrisA _______________________________________________ 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/QWR7PVJTMK6LBWKE2UYUXTDJHDYD25XK/ Code of Conduct: http://python.org/psf/codeofconduct/