Mypy: Stricter equality checks?

Created on 4 Mar 2016  路  9Comments  路  Source: python/mypy

It would be nice if there was a way to enforce a constraint on __eq__ -- maybe a warning? I almost never want to do the following

def test_operator(): # type: () -> None
    1 == "1"
# produces no complaints

While that check may make sense in a world of vanilla python, I'd argue it doesn't make much sense within mypy's world (especially if the arguments are explicitly typed as different types; i.e., one is not a subtype of the other).

feature needs discussion priority-0-high

Most helpful comment

It looks like this appears often, so I raise priority to high.

All 9 comments

Hm, I think you're right this should be flagged if the types don't overlap.

The operators !=, is and is not are similar. Also, mypy doesn't complain about things like 1 in ['x'] since it doesn't raise a runtime exception.

Attempting to specify a type other than Any or object with __eq__ results in an error message like this:

foo.py: note: In class "Foo":
foo.py:4: error: Argument 1 of "__eq__" incompatible with supertype "object"

(I'm adding this in case someone else is searching for this error.)

+1 would love to see this - had to troubleshoot a bug today that turned out to a stray , making an equality check fail because one side had accidentally become a tuple.

It looks like this appears often, so I raise priority to high.

+1, would love this feature. just had a bug with a missing parens, i.e. if func != 0:

Kind of similar to the above: I did forget a few times that obj.thing is a method, not a property, wrote if obj.thing: and got an always-on block of code.

+1 would love to see this too. I'm replacing a bunch of old string values with more type-safe enum objects and would love to get errors in places where my code needs updating, such as: if obj.enum_value == 'my_old_hard_coded_string_value'

@jstasiak Your case is a bit different, it is like https://github.com/python/mypy/issues/2073

Was this page helpful?
0 / 5 - 0 ratings