[Python-ideas] is in operator

Adam Olsen rhamph at gmail.com
Thu Sep 27 03:25:56 CEST 2007


On 9/26/07, Mathias Panzenböck <grosser.meister.morti at gmx.net> wrote:
> Sometimes I want to compare a "pointer" to more then one others. The "in" operator
> would be handy, but it uses the "==" operator instead of the "is" operator. So a "is
> in" operator would be nice. Though I don't know how easy it is for a newbie to see
> what does what.

There's many different ways you might want to do a comparison.  That's
why sorted() has a cmp=func argument.  A new API won't work though, as
dicts or sets need to know the hash in advance, and lists are O(n)
anyway (so there's little appropriate use.)

To solve your problem you should be using a decorate/undecorate
pattern, possibly encapsulated into a custom container type.  There
doesn't appear to be any in the python cookbook (so it may be a very
rare need), but assuming you did use a container type your code might
be rewritten as such:

if x in idset([a, b, c]):

But decorating is almost as simple:

if id(x) in [id(a), id(b), id(c)]:

(Caveat: id(obj) assumes you have another reference to the obj, to
prevent the identity from being reused.)


> # This:
> if x is in (a, b, c):
>         ...
>
> # would be equivalent to this:
> if x is a or x is b or x is c:
>         ...
>
> # And of course there should be a "is not in" operator, too:
> if x is not in (a, b, c):
>         ...
>
> # this would be equivalent to tis:
> if x is not a and x is not b and x is not c:
>         ...
>
>
> Hmmm, maybe a way to apply some kind of comparison between a value and more other
> values would be better. But that already exists, so screw this msg:
>
> if any(x is y for y in (a, b, c)):
>         ...
>
> if all(x is not y for y in (a, b, c)):
>         ...
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>


-- 
Adam Olsen, aka Rhamphoryncus



More information about the Python-ideas mailing list