[Python-Dev] Decimal <-> float comparisons in py3k.

Raymond Hettinger raymond.hettinger at gmail.com
Thu Mar 18 02:03:36 CET 2010


On Mar 17, 2010, at 5:02 PM, Greg Ewing wrote:

> Raymond Hettinger wrote:
> 
>> Python 3 doesn't need it because it is possible to not give a result
>> at all.  Python 2 does need it because we have to give *some*
>> result.
> 
> That's not true -- it's possible for comparisons to raise
> an exception in 2.x, and they sometimes do already:

Complex objects do not support __float__.  Decimal objects do.
If an object supports __float__, then a float comparison coerces 
its other argument via __float__ and the other argument
never gets a chance to raise an exception.

>>> class D:
	def __float__(self):
		return 3.14

	
>>> float(D())
3.1400000000000001
>>> float(complex(3.14))

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    float(complex(3.14))
TypeError: can't convert complex to float

>>> D() < 10.0
True
>>> complex(3.14) < 10.0

Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    complex(3.14) < 10.0
TypeError: no ordering relation is defined for complex numbers


Raymond




More information about the Python-Dev mailing list