Home > Back-end >  What's happening with the order of operations comparing "x is not y" vs "x is (n
What's happening with the order of operations comparing "x is not y" vs "x is (n

Time:05-21

What's happening in Python to make the following different?

>>> one = 1
>>> one is not False
True
>>> one is (not False)
False

Thinking of not as simply negating what comes after it, I would've thought they'd both have the same output as the second. What's happening to make them different? What are the "order of operations" of the first example?

CodePudding user response:

The first instance asks if one is not False which it is because "one" is 1 so the result is True. Here, the is not acts as its own operator.

The second instance asks if one is (not False) which is the same as asking if one is True, but one is not True it is 1. Here, the not is modifying the False to make it True

Keep in mind that is is not the same as ==.

For example 1 == True is True, but 1 is True is False.

CodePudding user response:

You can use the ast module to see how Python parses the two differently.

In the first case, the parser recognizes is not as a single (two-word) operator, with operands one and False.

>>> print(ast.dump(ast.parse("one is not False"), indent=4))
Module(
    body=[
        Expr(
            value=Compare(
                left=Name(id='one', ctx=Load()),
                ops=[
                    IsNot()],
                comparators=[
                    Constant(value=False)]))],
    type_ignores=[])

In the second case, the parser recognizes is as a single (one-word) operator, with operands one and not False.

>>> print(ast.dump(ast.parse("one is (not False)"), indent=4))
Module(
    body=[
        Expr(
            value=Compare(
                left=Name(id='one', ctx=Load()),
                ops=[
                    Is()],
                comparators=[
                    UnaryOp(
                        op=Not(),
                        operand=Constant(value=False))]))],
    type_ignores=[])
  • Related