default object comparison considered harmful?
A.T.Hofkamp
hat at se-162.se.wtb.tue.nl
Mon May 19 04:01:40 EDT 2008
On 2008-05-16, Kay Schluehr <kay.schluehr at gmx.net> wrote:
> On 16 Mai, 10:03, "A.T.Hofkamp" <h... at se-162.se.wtb.tue.nl> wrote:
>> Hello all,
>>
>> 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?)
>>
>> Sincerely,
>> Albert
>
> Are you sure you don't want to use a statically typed language that
> captures all type errors just by inspecting your source code?
yes.
The problem here is that it isn't caught at all, neither at 'compile' time nor
at run-time. That means that the Python language considers this proper code.
Whether you make that decision by inspecting source code or at run-time is
irrelevant here.
Unfortunaly, we have to maintain Python 2.3 compability.
As a solution, I have created a new BaseObject class as follows:
class BaseObject(object):
"""
Generic base class without default compare and hashing functions.
"""
def __cmp__(self, other):
""" Disable default compare method """
raise NotImplementedError
def __hash__(self):
""" Disable default hashing method """
raise NotImplementedError("Implement me in class '%s'"
% self.__class__.__name__)
Sincerely,
Albert
More information about the Python-list
mailing list