How come a check of string > int evaluates to True?
>>> strver = "1"
>>> ver = 1
>>> strver > ver
True
>>> strVer2 = "whaat"
>>> strVer2 > ver
True
Did some more experimenting:
>>> ver3 = 0
>>> strVer2 > ver3
True
I think there should be an error when trying to compare but it seems like nothing is built to handle such an error, or assert should be used but that can be dangerous if python code is being run with -O flag!
Source: How does Python compare string and int?, which in turn quotes the CPython manual:
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.
From the SO answer:
When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames:
>>> [1, 2] > 'foo' # 'list' < 'str'
False
>>> (1, 2) > 'foo' # 'tuple' > 'str'
True
>>> class Foo(object): pass
>>> class Bar(object): pass
>>> Bar() < Foo()
True
...so, it's because 's' comes after 'i' in the alphabet! Luckily, though, this slightly odd behavior has been "fixed" in the implementation of Python 3.x:
In Python 3.x the behaviour has been changed so that attempting to order an integer and a string will raise an error:
Seems to follow the principle of least astonishment a little better now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With