# checking if two things do not equal None

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Mar 30 07:54:11 CEST 2014

```On Sun, 30 Mar 2014 13:15:18 +1100, Chris Angelico wrote:

> On Sun, Mar 30, 2014 at 1:04 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On Sat, 29 Mar 2014 17:07:20 -0400, Roy Smith wrote:
>>
>>> I certainly agree that things like
>>>
>>>> if a is not b is not None: ...
>>>
>>> belong in an obfuscated coding contest.
>>
>> Apart from the fact that I got it wrong (that's what happens when I
>> post at 6am after being up all night, thanks for the correction Lele),
>> if you consider chained comparisons to be "obfuscated", I think you're
>> not really fluent at Python. The OP even suggested  `a != None != b` so
>> I think that (s)he at least understands chained comparisons.
>>
>> However, I agree with Johannes that inverted conditions (using "not")
>> are sometimes harder to reason about than "regular" conditions.
>
> Chained comparisons where you're checking a single variable against two
> constants make perfect sense:
>
> 2 < x < 5
>
> Chained comparisons where you check a single constant against two
> variables don't, so much:
>
> x < 2 < y
>
> What exactly does that mean, and why is it written that way?

It checks that 2 is strictly bounded between x on the left and y on the
right, i.e. that 2 is inside the open interval x...y. I don't know why
you think that's unclear. But then I do have a maths background and I'm
used to chaining comparisons.

Write it like this:

low = x
high = y
a = 2

low < a < high

Does that make more sense? Well-chosen names are good. The fact that a is
a constant rather than a variable is no big deal:

low < 2 < high

> We can
> figure out how the interpreter will parse that, but does that correspond
> to the programmer's intention?

That applies to just about anything:

(x % 2 == 1) or (x > 0)

What that my intention, or did I intend to write

(x % 2 == 0) and (x < 0)

At some point you just have to accept that, in the absence of clearly
nonsensical code or a contradiction between the documentation and the
behaviour (i.e. a bug), the programmer will have written what she
intended to write.

> It'd be more useful but less clear if one of the conditions points the
> other way:
>
> x < 2 > y
>
> which checks that they're both less than two,

which is quite different from what you wrote the first time.

> but IMO in a less-than-clear way.

That's an understatement. If I saw code chaining comparisons in that
fashion, I would assume the second operator > was a typo.

Chaining less-than and greater than operators should, for clarity, always
be written in a single order. E.g. a <= b < c < d, not a <= b < d > c.

(The second contains a subtle bug too.)

--
Steven D'Aprano
http://import-that.dreamwidth.org/

```