/var/log/mandarg

Mandar Gokhale's weblog on the internets

Comparisons Between Operands of Different Types

Recently, a colleague of mine tracked down a bug which was, in essence, caused by the fact that one side of a comparison in Python was a string, and the other was an integer, which led to behaviour that was sometimes expected and sometimes not.

1
2
3
4
>>> '45' > 43
True
>>> '41' > 43
True

This is one of the more unintuitive parts for Python for me. Intuitively, I would expect some sort of a TypeError if I am trying to compare things that are not of the same type. But, apparently, in Python, when you compare two items of distinct types, Python compares the types themselves.

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently.

I looked at this in a couple of other languages. Javascript seems to do implicit type conversion,

1
2
3
4
> '45' > 43
true
> '41' > 43
false

…whereas Ruby seems to behave fairly sanely, throwing an error – just like I expect. Perhaps it’s time to start using Ruby a bit more for my small scripts (though it often seems to lead to more time spent yak shaving than Python in the average case).

1
2
3
4
5
irb(main):001:0> '45' > 43
ArgumentError: comparison of String with 43 failed
    from (irb):1:in `>'
    from (irb):1
    from /usr/bin/irb:12:in `<main>'

❧ Suggestions, comments, etc. can be emailed to comments@mandarg.com