[BangPypers] Python comparisons

Anand Chitipothu anandology at gmail.com
Sat Dec 5 04:54:47 EST 2015


On Sat, Dec 5, 2015 at 12:56 PM, Noufal Ibrahim KV <noufal at nibrahim.net.in>
wrote:

>
> So I came across this today..
>
> >>> class Number(object):
> ...    def __init__(self, n):
> ...       self.n = n
> ...
> >>> m = Number(10)
> >>> n = Number(5)
> >>>
> >>> m < n
> True
>
> This is documented like so
>
> > If no __cmp__(), __eq__() or __ne__() operation is defined, class
> > instances are compared by object identity (“address”).
>
> over here
> https://docs.python.org/2/reference/datamodel.html#object.__cmp__
>
> It seems a rather arbitrary thing to do. Why is it implemented at all?
> I'd expect it to just break with a TypeError similar to what would
> happen if I do
>
> >>> m + n
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unsupported operand type(s) for +: 'Number' and 'Number'
> >>>
>

Thats why you should use Python 3. Here is what you get with Python 3.

>>> class Foo: pass
...
>>> a = Foo()
>>> b = Foo()
>>>
>>> a < b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: Foo() < Foo()

That would give True in Python 2.

Anand


More information about the BangPypers mailing list