Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

It's not implemented directly on bool.

>>> True.__lt__(2)
AttributeError: 'bool' object has no attribute '__lt__'

And it's apparently not implemented on int either:

>>> super(bool, True).__lt__(2)
AttributeError: 'super' object has no attribute '__lt__'

There is no reflected version of __lt__ for 2 to control the operation, and since int type is not a subclass of bool that would never work anyway.

Python 3 behaves as expected:

>>> True.__lt__(2)
True

So, how is True < 2 implemented in Python 2?

share|improve this question
    
Via an implicit conversion to an integer maybe? – Carcigenicate yesterday
    
You might find this trick funny: [exprFalse, exprTrue][condition] is equivalent to exprTrue if condition else exprFalse – BlackBear 21 hours ago
3  
@BlackBear except that it evaluates both. print("True") if condition else print("False") vs [print("False"), print("True")][condition]. – immibis 21 hours ago

True is equal to 1 in Python (which is why it's less than 2) and bool is a subclass of int (basically, False and True are 0 and 1 with funky repr()s).

As to how comparison is implemented on integers, it uses __cmp__(), which is the old-school way of writing comparisons in Python. (Python 3 doesn't support __cmp__(), which is why it's implemented as __lt__() there.) See https://docs.python.org/2/reference/datamodel.html#object.__cmp__

share|improve this answer
2  
Ah, yes that's it. I'd forgotten about ol' __cmp__. Thanks! – wim yesterday
3  
Be sure to mark kindall's post as correct if it helped you @wim – Andrew 10 hours ago

You didn't find super(bool, True).__lt__ because int uses the legacy __cmp__ method instead of rich comparisons on Python 2. It's int.__cmp__.

share|improve this answer

True is a just name that refers to an object of type int, specifically value 1. Expression True < 2 is equal to 1 < 2. Same, False is equal to 0. In Python 2 you have a method __cmp__, that returns 0 if values are equals, -1 if is one value too greater than other value and 1 if is one value too less than other value. Example:

>>> True.__cmp__(1)
0
>>> True.__cmp__(0)
1
>>> True.__cmp__(-1)
1
>>> True.__cmp__(0)
1
>>> True.__cmp__(1)
0
>>> True.__cmp__(2)
-1

In Python 3 you have a __lt__ and __gt__ methods that are equivalents of < and >.

share|improve this answer
    
True is a just name that refers to an object of type int <-- I don't think that's right, the type of True is bool. A subclass of int. The subclass could, in principle, override the operation True < 2 to behave differently than 1 < 2. – wim 16 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.