3

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!

kassak
  • 3,974
  • 1
  • 25
  • 36
Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197
  • 2
    there is a similar question with a nice answer: http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int – Verena Haunschmid Jan 28 '14 at 07:45
  • This is only a guess here, but I'd say that this behavior exist so that one can put both strings and int in ordered containers (which require ordering of the elements, so those elements must be comparable). So I guess a choice was made that strings are ranked "higher" than int, no matter their values. – ereOn Jan 28 '14 at 07:46
  • 1
    "I think there should be an error" - the developers agree! They changed the behavior to raise a `TypeError` in Python 3. – user2357112 Jan 28 '14 at 07:56

1 Answers1

9

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.

Community
  • 1
  • 1
sundance
  • 2,905
  • 4
  • 21
  • 31