checking if two things do not equal None

Chris Angelico rosuav at gmail.com
Sat Mar 29 22:15:18 EDT 2014


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? We can
figure out how the interpreter will parse that, but does that
correspond to the programmer's intention?

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, but IMO in a less-than-clear way.

ChrisA



More information about the Python-list mailing list