PyWart: Language missing maximum constant of numeric types!

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Feb 24 16:31:28 CET 2012


On Fri, 24 Feb 2012 10:21:45 -0500, Mel Wilson wrote:

> Rick Johnson wrote:
> 
>> I get sick and tired of doing this!!!
>> 
>> if maxlength == UNLIMITED:
>>     allow_passage()
>> elif len(string) > maxlength:
>>     deny_passage()
>> 
>> What Python needs is some constant that can be compared to ANY numeric
>> type and that constant will ALWAYS be larger!
> 
> Easily fixed:
> 
> 
> 
> class Greatest (object):
>     def __cmp__ (self, other):
>         if isinstance (other, Greatest):
>             return 0
>         return 1
>         
>     def __hash__ (self):
>         return id (Greatest)

__cmp__ no longer exists in Python 3, so this solution could only work in 
Python 2.

Here's a version using rich comparisons:

class Greatest:
    __eq__ = __le__ = lambda self, other: isinstance(other, type(self))
    __ne__ = __gt__ = lambda self, othr: not isinstance(othr, type(self))
    __lt__ = lambda self, other: False
    __ge__ = lambda self, other: True
    __hash__ = lambda self: 42


-- 
Steven



More information about the Python-list mailing list