cat /dev/brain

Weirdness in python2

So a friend of mine is learning python and was fooling around in the interactive console. They accidentally ran:

'str' > 19
# But they meant to run
'str' > '19'

Can you guess what that evaluated to? Conventional thought would suggest a TypeError, but in fact that evaluates to True. Odd right? That's what I thought so I asked #python on freenode. lvh gave me the explanation which is the only one that makes sense and seems plausible at the same time. The hint (s)he gave me was 'i' comes before 's'.

In python2, this is something that is just built-in for some unknown reason and it boils down to the fact that the class names ('str' and 'int') are used for comparison. Luckily enough, this has been fixed in python3 and it raises the expected Error, e.g.,:

>>> 'str' > 19
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

Thanks to the #python community for explaining this. It was a real head-scratcher for me and I would never have guessed this.