2

My code accidentally compared a dict to an int using an inequality and it turns out that any dict evaluates True when tested to be greater than an int.

d = {'a': 1, 'b': 2}
d > 0
Out[20]: True
d > 10e99999999999999
Out[21]: True

Why does this happen instead of a type error?

This happens running on Python 2.7

hamx0r
  • 4,081
  • 1
  • 33
  • 46

3 Answers3

8

From the Python 2.7 documentation:

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).

The Python 3.3 documentation has instead this:

The <, <=, > and >= operators will raise a TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.

Meaning what you are seeing is no longer possible as of Python 3, but instead such comparisons yield a TypeError like you expected.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
3

First, the Python team agrees with you -- in Python 3, this is an error.

In earlier Python versions everything is comparable with each other, to make it consistent some types always sort before other types.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

Apparently in Python 2.7 Dictionaries are always greater than integers. Apparently it's alphabetical?

toonarmycaptain
  • 2,093
  • 2
  • 18
  • 29