Simple Python question for some

Chris Angelico rosuav at gmail.com
Sun Oct 28 20:18:46 EDT 2012


On Mon, Oct 29, 2012 at 10:51 AM, Mark L. Hotz <mlhotz at gmail.com> wrote:
> At the IDLE prompt, when I enter “b” > 99, it responds True. In fact, it
> doesn’t matter which number is entered here, “b” is always greater (e.g. “b”
>> 1 == True; “b” > 100000 == True, or “b” < 99 = False).

To Python, different object types are completely different.
Incidentally, with issues like this, it's worth mentioning which
version of Python you're using - though in this case, it's clear
you're using Python 2. As of version 3, behaviour is different:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> "b" > 99
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    "b" > 99
TypeError: unorderable types: str() > int()


As of Python 2, there's a slightly esoteric rule as described here:
http://docs.python.org/2/library/stdtypes.html#comparisons
"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."

So since "str" is greater than "int", "b" is greater than 99.

Fortunately, Python does NOT have arcane rules for comparing numbers
as though they were strings. Notably:

>>> "100" == 100
False

Which means that strings will ALWAYS be compared as strings, and
numbers will ALWAYS be compared as numbers, and ne'er the twain shall
conflict. I can trust Python to compare MD5 hashes reliably:

>>> "912128034267498495410681495015e0" != "00912128034267498495410681495015"
True

Of course, I'm not pointing fingers at any other languages here, but
this is a known security hole in one rather widely-used one.

ChrisA



More information about the Python-list mailing list