-1

I am curious about the precedence of "x is not True" in Python. At first, I assume it means "!= True", but then I though the "not True" is surely of higher precedence that "is not". Yet the following seems to indicate the latter:

>>> 4 is not True    
True    
>>> not True    
False     
>>> 4 is False     
False     
>>> 4 is (not True)
False

It seems Python interprets "is not True" as a single expression, rather than "is (not True)" which is equivalent to "is False".

I am not new to Python programming, yet I have not thought deeply about this before. Can I safely assume that "is not" is an operator in itself that has higher parsing precedence that "not True"?

aaa90210
  • 11,295
  • 13
  • 51
  • 88
  • 1
    "Is not" is indeed an operator in itself: https://stackoverflow.com/questions/4485180/python-is-not-operator – aaa90210 Apr 29 '20 at 22:12

4 Answers4

6

No, it isn't. x is not True will be true for any value x that is not the singleton object True

It seems Python interprets "is not True" as a single expression, rather than "is (not True)" which is equivalent to "is False".

Precisely. You can actually see this in the disassembled bytecode, is not is its own comparison operation

>>> import dis
>>> dis.dis("x is not True")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (True)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
>>>
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
5

is not is an operator, the opposite of is.

x is not y

means

not (x is y) 

It does not mean

x is (not y)

E.g.

4 is not False

is True (it means not (4 is False))

whereas

4 is (not False)

is False (since not False evaluates to True, not the value 4).

khelwood
  • 55,782
  • 14
  • 81
  • 108
2

Yes, in python, is not is an operator of its own, not a composition of is and not. And the is not operator has a higher precedence than the not operator. If you want, you can check this in Python's documentation

Alejandro De Cicco
  • 1,216
  • 3
  • 17
1

4 (is not) True (The bool), Because 4 is 4 (The int).

Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30