Why doesn't comparing an int to a str raise a TypeError?

Viewed 101

Why does this code print "not equals" instead of throwing a TypeError?

int_num = 1
str_num = "2"

if str_num == int_num:
    print("equal")
else:
    print("not equal")
2 Answers

From the current Python documentation for Comparisons:

Objects of different types, except different numeric types, never compare equal. The == operator is always defined...

(Emphasis mine.)

How comparisons are defined for standard types:

Objects of different types, except different numeric types, never compare equal. The == operator is always defined but for some object types (for example, class objects) is equivalent to is. The <, <=, > and >= operators are only defined where they make sense; for example, they raise a TypeError exception when one of the arguments is a complex number.

Non-identical instances of a class normally compare as non-equal unless the class defines the __eq__() method.

Equality would work on any objects though:

By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented.

Related