Search code examples
pythonfunctionintoperatorspython-2.x

in Python 2.x, why is the > operator supported between function and int?


In Python 2.x, the following code produces an error, as expected:

>>> def a(x): return x+3 
...
>>> a+4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'function' and 'int'

However, the following is allowed:

>>> a < 4
False

Why is the + operator not defined for function and int, but the < operator is?


Solution

  • In Python 2, objects are orderable by default. Types have to explicitly opt out (e.g. complex raises an exception when you try to make greater or lesser than comparisons).

    CPython (the original Python implentation) orders None before numbers, then numbers before everything else. Objects that don't implement ordering themselves, are compared by their type name; so function sorts before instances of the class Zippedeedoodah. Other implementations are free to pick different orders.

    Python does this to support sorting of heterogeneous lists. Quoting the Value comparisons documenation:

    The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects do not need to have the same type.

    The default order comparison (<, >, <=, and >=) gives a consistent but arbitrary order.

    In Python 3, only objects that explicitly support ordering are supported, everything else throws an exception:

    >>> def a(x): return x+3 
    ... 
    >>> a < 4
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unorderable types: function() < int()