3

I have a trivial class that has no members, but I can apparently still use relational comparison operators:

>>> class A(object): pass
... 
>>> 1 < A()
True
>>> A() < 1
False

Furthermore, any int or double compares less than A(). Strings compare greater than A():

>>> 'hi' < A()
False

A() inconsistently compares against itself:

>>> A() < A()
True
>>> A() < A()
False

But never to B:

>>> class B: pass
... 
>>> A() < B()
False
>>> A() < B()
False
>>> A() < B()
False

How is this not an error? What sorcery is this?!

Barry
  • 286,269
  • 29
  • 621
  • 977
  • 1
    This has been asked a lots of times: [**CPython implementation detail**: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.](https://docs.python.org/2/library/stdtypes.html#comparisons) – Ashwini Chaudhary Jul 31 '15 at 20:17
  • There is no sourcery. There is only the decision in Python (rescinded for Python 3) to make everything orderable. – Martijn Pieters Jul 31 '15 at 20:18
  • And without explicit ordering instances of the same class are ordered by their memory id. `A()` is consistently ordered, but you need to avoid letting Python re-use the memory location.. – Martijn Pieters Jul 31 '15 at 20:19
  • @AshwiniChaudhary Pick a duplicate and close? – Barry Jul 31 '15 at 20:30
  • For your `A() < A()` comparison, the order is determined by their `id()` address. This means they can end up anywhere on the heap and it is easily possible for the second object to get a lower memory address than the first. Or vice versa. – Martijn Pieters Jul 31 '15 at 21:22

1 Answers1

0

It's Python sorcery!

Python has stock comparison methods which it will add to your class unless you override them.

I would imagine that you're getting the result of whether the object's handle is less than the other, so you won't necessarily get a meaningful result (or the result you expected), which is why we overload these comparison operators to give more meaningful results.

Hope this helps!

SteJ
  • 1,491
  • 11
  • 13