What Are Built-in Python 3 Types That Can Be Compared To Each Other?
Solution 1:
All these are valid statements (and they all evaluate to True
):
0 < True0 < 1.0. < True
{0} < frozenset((0, 1))
The only thing that may look odd here is that 0. == False
and 1. == True
.
On the other hand, you can still reproduce what python 2 does by casting your value to an str
before comparing it (this also evaluate to True
):
str(5) < 'hello'
If you really need this behaviour you can always have a function that will cast/compare. That way you'll guarantee that objects of different types will always compare the same way, which seems to be the only constraint in python 2.
deflt(a, b):
returnstr(a) < str(b)
Or maybe even better, you can cast only when needed:
deflt(a, b):
try:
return a < b
except TypeError:
returnstr(a) < str(b)
On the other hand, as suggested in the comments, in CPython's implementation, it seems like comparison is done in the following way:
deflt(a, b):
try:
return a < b
except TypeError:
if a isNone:
returnTrueif b isNone:
returnFalseifisinstance(a, numbers.Number):
returnTrueifisinstance(b, numbers.Number):
returnFalsereturnstr(type(a)) < str(type(b))
Solution 2:
I had already looked this up on the web before, and it appears they are indeed unsortable in Python 3, apart from the few special cases mentionned above.
The change usually manifests itself in sorting lists: in Python 3, lists with items of different types are generally not sortable. If you need to sort heterogeneous lists, or compare different types of objects, implement a key function to fully describe how disparate types should be ordered. Source
I don't know why, but some found ways to reproduce the behavior of Python 2 using Python 3.
Maybe you should take a look at this or that. This question also highlighted the change in 2011:
Found it: Buried in PEP 3100: "Comparisons other than == and != between disparate types will raise an exception unless explicitly supported by the type"
Post a Comment for "What Are Built-in Python 3 Types That Can Be Compared To Each Other?"