Skip to content

Comparison linting between different types #1411

Answered by erictraut
theFong asked this question in Q&A
Discussion options

You must be logged in to vote

Most classes support equality checks between arbitrary types. For example, the following code runs without an exception:

x = 1
y = "hi"
print(x == y) # False
print(y == None) # False

This is not only legal at runtime, it's also specifically allowed by the __eq__ and __ne__ methods inherited from object by most classes.

class object:
    ...
    def __eq__(self, o: object) -> bool: ...
    def __ne__(self, o: object) -> bool: ...

You're free to declare __eq__ and __ne__ methods on your custom class that accept narrower types than object. For example:

class A:
    # Allow comparison only with other "A" instances.
    def __eq__(self, o: "A") -> bool: ...
    def __ne__(self, o: "A") -> bool:…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@theFong
Comment options

Answer selected by theFong
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants