[Tutor] 0 > "0" --> is there a "from __future__ import to make this raise a TypeError?

Steven D'Aprano steve at pearwood.info
Tue Oct 13 19:06:19 EDT 2015


On Mon, Oct 12, 2015 at 04:12:57PM +0000, 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?

I don't believe so.

You could write your own comparison functions and use those:


def gt(a, b):
    if type(a) is type(b):
        return a > b
    raise TypeError

if gt(this, that): ...


but there's no way to change the behaviour of the comparison operators > 
etc themselves, nor of list.sort.

In hindsight, this should have been a __future__ import, but it's too 
late now :-(



-- 
Steve


More information about the Tutor mailing list