[Tutor] 0 > "0" --> is there a "from __future__ import to make this raise a TypeError?
Albert-Jan Roskam
sjeik_appie at hotmail.com
Mon Oct 12 16:24:36 EDT 2015
----------------------------------------
> To: tutor at python.org
> From: emile at fenx.com
> Date: Mon, 12 Oct 2015 09:25:00 -0700
> Subject: Re: [Tutor] 0> "0" --> is there a "from __future__ import to make this raise a TypeError?
>
> On 10/12/2015 9:12 AM, Albert-Jan Roskam wrote:
>> Hi,
>>
>>
>> In Python 2 one can do silly apple-pear comparisons such as 0> "0".*) "CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.". In Python3 this has been fixed (it raises a TypeError). Is there a way to emulate this behavior in Python 2?
>>
>>
>>
>> *)http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int
>>
>
> See if implementing __cmp__ gets you what you're looking for.
>
> See http://www.rafekettler.com/magicmethods.html#comparisons for more info.
>
> Emile
Hi Emille,
Maybe like so? Is it possible to call __cmp__ wiithout the need to make an instance? I would find it nicer if I could do Cmp(42) == "42".
Also, the two if/elifs don't feel quite right/generic.
# -*- coding: utf-8 -*-.
class Cmp(object):
"""Compare objects the Python 3 way: no apple-pear comparisons allowed!
>>> x = Cmp() # doctest: +IGNORE_EXCEPTION_DETAIL
>>> x(42) == "42"
Traceback (most recent call last):
...
TypeError
>>> x(42) == 42
True
>>> x(42) == 42.1
False
>>> x("42")> 0
Traceback (most recent call last):
...
TypeError
"""
def __call__(self, x):
self.x = x
return self
def __cmp__(self, y):
#print "__cmp__"
self.y = y
if isinstance(self.x, (str, unicode)) and hasattr(self.y, "__int__"):
raise TypeError
elif isinstance(self.y, (str, unicode)) and hasattr(self.x, "__int__"):
raise TypeError
return -1 if self.x < self.y else 0 if self.x == self.y else 1
if __name__ == "__main__":
import doctest
doctest.testmod()
More information about the Tutor
mailing list