IssamLaradji
IssamLaradji

Reputation: 6865

Broadly override an operator (Type check with "==")

Is there a way to make Python (3.6.3) throw an error for comparing two objects with different types? As an example, I would like "2" == 2 to throw an error rather than return False.

Naively, I could add type(a) == type(b) along with a == b in the conditional, but I am hoping for a simpler solution; like replacing == with another symbol(s).

In a similar context, I like that in Python comparing between a str and an int results in a type mismatch error. For example, "2" >= 2 throws an error. But I am looking for the same behavior for an equality ==.

PS: I think I miscommunicated the question a bit. To be precise, I am looking for a simple alternative to == that throws an error with different types; instead of overriding the behavior of == broadly.

Upvotes: 1

Views: 79

Answers (1)

John Gordon
John Gordon

Reputation: 33335

Here's a relatively straightforward solution, but it does require you to edit all your existing uses of ==.

Change this:

if a == b:

To this:

if isequal(a, b):

def isequal(a, b):
    assert type(a) == type(b)
    return a == b

Upvotes: 3

Related Questions