wim wim - 24 days ago 19
Python Question

How is True < 2 implemented?

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?

Answer

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__.

Comments