9

So I was looking at some code online and I came across a line (at line 286):
if depth > 0 and best <= -MATE_VALUE is None and nullscore > -MATE_VALUE:

The part I had trouble understanding was the best <= -MATE_VALUE is None.

So I fired up the interpreter to see how a statement such as value1 > value2 is value3 work.
So I tried

>>> 5 > 2 is True
False

>>> (5 > 2) is True 
True

>>> 5 > (2 is True) 
True


My Question

Why is 5 > 2 is True not True? And how do these things generally work?

Thanks.

Kidus
  • 1,785
  • 2
  • 20
  • 36
  • 3
    Look up operator chaining. This is actually not a precedence issue. The first is treated logically as `(5 > 2) && (2 is True)`, which is why/how Python allows a meaningful `a < x < b` construct. There are duplicates about this. – user2864740 Aug 24 '15 at 12:22
  • 1
    http://stackoverflow.com/questions/25753474/python-comparison-operators-chaining-grouping-left-to-right , http://stackoverflow.com/questions/101268/hidden-features-of-python/101945#101945 , http://stackoverflow.com/questions/25103085/chaining-is-operators , http://stackoverflow.com/q/6074018/2864740 – user2864740 Aug 24 '15 at 12:25
  • 3
    FWIW, this line seems very strange to me -- it's not clear to me when this expression will ever be True. If MATE_VALUE is a number (which presumably it is because of `-MATE_VALUE`), then it will never be None (if it were, the `-` wouldn't work.) So if the line doesn't throw an exception, won't it always return False? – DSM Aug 24 '15 at 12:31
  • 3
    I think the person who wrote that is probably more confused than you are. Neither the actual interpretation (`best <= -MATE_VALUE and -MATE_VALUE is None`) nor either of the plausible incorrect interpretations (`(best <= -MATE_VALUE) is None` or `best <= (-MATE_VALUE is None)`) makes any sense. – chepner Aug 24 '15 at 13:15

2 Answers2

8

You're seeing python's operator chaining working

5 > 2 is True

Is equivalent to

5>2 and 2 is True

You can see this in that

>>> 5>2 is 2

Returns True.

muddyfish
  • 3,530
  • 30
  • 37
3

First, 5 > 2 is True is equivalent to (5 > 2) and (2 is True) because of operator chaining in python (section 5.9 here).

It's clear that 5 > 2 evaluates to True. However, 2 is True will evaluate to False because it is not implicitly converted to bool. If you force the conversion, you will find that bool(2) is True yields True. Other statements such as the if-statement will do this conversion for you, so if 2: will work.

Second, there is an important difference between the is operator and the == operator (taken from here):

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

>> [1,2] is [1,2]
False

>> [1,2] == [1,2]
True

While this does not have an immediate impact on this example, you should keep it in mind for the future.

Community
  • 1
  • 1
Daniel Lenz
  • 3,334
  • 17
  • 36