default object comparison considered harmful?

Peter Otten __peter__ at web.de
Fri May 16 04:27:17 EDT 2008


A.T.Hofkamp wrote:

> Yesterday we found the cause of a bug that has caused problems for a long
> time. It appeared to be the following:
> 
> class A(object):
>     pass
> 
> print min(1.0, A())
> 
> which is accepted by Python even though the A() object is not numerical in
> nature.
> 
> The cause of this behavior seems to be the compare operation of the object
> class.
> 
> 
> Is there a way to disable this behavior in Python (other than deriving a
> new 'object-like' class that doesn't do comparisons?)

As Bruno says, this will change in 3.0:

# 3.0
>>> class A: pass
...
>>> min(1.0, A())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    TypeError: unorderable types: A() < float()

For 2.5 and above you can provide a key function as a workaround:

# 2.5
>>> class A(object): pass
...
>>> min(1, A(), key=float)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: float() argument must be a string or a number

Peter



More information about the Python-list mailing list