3

during a personal project I needed to evaluate if two variables were equal, but not None. So the condition should be True if they are both equal (a=5, b=5), but not in other cases, or when they are both None (a=None, b=None), it should be False

So I typed in my interpreter a == b is not None and had the behavior I wanted.

Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = None
>>> b = None
>>> a == b is not None
False
>>> a = 5
>>> a == b is not None
False
>>> b = 5
>>> a == b is not None
True
>>>

But I wanted to double check if this was the intended behavior, as in a special case in the evaluation of condition (like the phrase x is not None which means not x is None) ? Or maybe it is just the normal way Python would evaluate it ?

Because if we evaluate it normally, we would first check if a == b, and then compare that with is not None which would always result in True, but in reality when we test it, the behavior is different. Also I have never in 5 years of Python programming seen this condition, so I find it pretty rare, therefore I am not sure if it was already documented

martineau
  • 119,623
  • 25
  • 170
  • 301
Nathan Marotte
  • 771
  • 1
  • 5
  • 15
  • 1
    I recently Answered another similar question which may have some further surprising/helpful examples! https://stackoverflow.com/questions/70689599/the-order-of-operations-in-python – ti7 Jan 13 '22 at 23:07

1 Answers1

8

These are chained comparisons. It's exactly equivalent to

a == b and b is not None

in each of the cases.

Little more gentle introduction available here:

This is most commonly used (in my experience) with < or >, e.g.

# reads like a normal math expression
if 0 < x < 10:
    print('valid range')  # or whatever. 
Cody Piersall
  • 8,312
  • 2
  • 43
  • 57