Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is True < 2 implemented?

Tags:

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?

like image 443
wim Avatar asked Nov 04 '16 22:11

wim


People also ask

What are implementation methods?

The implementation methodology is the method by which the projects are technically and operationally implemented in the field, most often by using contractors or subcontractors. Typical implementation models are Energy Performance Contracting, Energy Supply Contracting and Separate Contractor Based.


1 Answers

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, Python 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__

like image 113
kindall Avatar answered Sep 28 '22 03:09

kindall