A Universe Set
Duncan Booth
duncan.booth at invalid.invalid
Tue Oct 17 05:53:21 EDT 2006
Jorgen Grahn <grahn+nntp at snipabacken.dyndns.org> wrote:
>> >> - the wildcard object, which compares equal to everything else
>>
> [Paul]
>> Paul> class MatchAny(object):
>> Paul> def __cmp__(self,other):
>> Paul> return 0
>>
>> Paul> wild = MatchAny()
>
> FWIW, I define __eq__ in the one I (infrequently) use.
The advantage to using __eq__ is that it fails to work correctly less often
than __cmp__. Compare skip's example where comparison against datetime give
the wrong answer 100% of the time with __cmp__ and 50% of the time with
__eq__/__ne__:
>>> import datetime
>>> class MatchAny(object):
def __cmp__(self,other):
return 0
>>> wild = MatchAny()
>>> print wild == datetime.datetime.now()
False
>>> print datetime.datetime.now() == wild
False
>>> print wild != datetime.datetime.now()
True
>>> print datetime.datetime.now() != wild
True
>>> class MatchAny(object):
def __eq__(self,other):
return True
def __ne__(self,other):
return False
>>> wild = MatchAny()
>>> print wild == datetime.datetime.now()
True
>>> print datetime.datetime.now() == wild
False
>>> print wild != datetime.datetime.now()
False
>>> print datetime.datetime.now() != wild
True
>
>> ...
>>
>> You're at the mercy of the comparison machinery implemented by
>> individual classes. Executing this script (using any of Python 2.3
>> through what's currently in the SVN repository):
> ...
>
> Oh. /Is/ there a way of making it work, then? If we ignore the
> problems with having such objects in the first place, that is.
>
In a contained environment, it can be made to work 'well enough'. So if you
are writing unit tests and want a wildcard element to include inside data
structures, AND you can guarantee that you always assert in the order
expected,actual, then you can probably get away with it. That's assuming
you remembered to use __eq__/__ne__ rather than __cmp__.
For an object safe to let out in the wild though there isn't any way to
implement it.
More information about the Python-list
mailing list