I'm still confused by this #python oddity, originally posted by @driscollis:
x = True
y = False
print(x is (not y))
print(not x is y)
print(not (x is y))
print((not x) is y)
print(x is not y)
print(x == (not y))
print(not x == y)
print(not (x == y))
print((not x) == y)
print(x == not y)
Why is the last line a syntax error when the rest are fine?
@sassdawe @driscollis I could understand an "operator precedence" issue being solved with parentheses, but something like x == !y works fine in other languages. Also, why does "x is not y" work but "x == not y" doesn't? I would expect is and == to be syntactically interchangeable.
@peterdrake @driscollis Talking about oddities, You could just be like C and not support Booleans for the longest time. : P
Reasoning being, you can't store a single bit on byte/word based machines.
@peterdrake
‘==‘ and ‘not’ are both operators. It’s like writing ‘5 + - 4’ instead of ‘5 + (-4)’.
Beware of ‘is’ in boolean expressions. It’s testing for object identity not equality and thus should not replace ‘==‘ in boolean operations.
True: ‘a is b => a == b’
False: ‘a == b => a is b’
@spencer @peterdrake @driscollis The worst is that `is` will work a lot of the time in arithmetic, because numbers from -1 to 255 are singletons in CPython.
So you might write your code, test it, believe it worked, and then one day have it mysteriously fail.
`is` guaranteed to work for booleans, though.
@TomSwirly
Yes it works for booleans because there’re existing (only) two distinctive objects {True, False} of type bool. Ambiguity arises when you’re going to implement __bool__, __eq__, etc. for your own types.
@peterdrake @driscollis
@spencer @driscollis ... but Python is perfectly happy to evaluate 5 + - 4, because unary - has higher precedence than +, so this is parsed as 5 + (- 4).
This is the path to the solution, though. == has higher priority than not, so x == not y just doesn't have any reasonable parse tree. (In Java, in contrast, ! has higher priority than ==. I don't know why Python chose to do it differently.)
So how does x is not y work? Because, surprisingly, "is not" is one operator!
@peterdrake
Thanks for clarifying. I didn’t even recognize the „is not“ operator beneath all other comparisons.
@driscollis
@peterdrake @driscollis I don't do Python, butt maybe a the
( )
missing aroundnot