4 ms·
You don't want it to raise an exception at run-time, but you probably want it to be a static type error: two things that aren't the same type can never be equal
by wk_end 6y ago
You don't want it to raise an exception at run-time, but you probably want it to be a static type error: two things that aren't the same type can never be equal, so if you're bothering to compare them you're at best wasting cycles and at worst making a dumb mistake.
In your example, `foo` could be marked (in mypy) a `Union[Foo, int]`, which would be a reasonable value to compare against an `int` and not a type error.
- joshuamorton 6y agoBut there are times you want heterogenous types to compare with ==. Your approach isn't compatible with ad-hoc polymorphism. For an example, consider `np.eye(4) == 1`. In this, you're comparing a doubly nested array of floats with a scalar int, but the operation is well defined (vectorized equality comparison). And yes, it should be feasible to typecheck that operation.
- coldtea 6y ago>two things that aren't the same type can never be equal Well, actually as long as they implement the right dundermethods, they can totally be.
- codethief 6y agoBesides, there is a difference between the actual type of the objects `a` and `b` in `a == b` and the structural type you specify in an annotation. For instance: from typing import Protocol class MyClass: def method_a(self) -> None: ... def method_b(self) -> None: ... class ProtocolA(Protocol): def method_a(self) -> None: ... class ProtocolB(Protocol): def method_b(self) -> None: ... def compare(a: ProtocolA, b: ProtocolB): if a == b: print("a == b") else: print("a != b") a = MyClass() b = MyClass() compare(a, b) Clearly, you would expect the output to be "a == b".
- magicalhippo 6y ago> two things that aren't the same type can never be equal You're saying is that an 8-bit number can never be equal to a 16-bit number, or a 32-bit number, or a... I hope you agree that's ridiculous.
- cygx 6y agoI hope you agree that's ridiculous. No comparison without explicit casts is a valid design choice. I think Ada and Rust work that way, though I've never used either language and might be mistaken...
- magicalhippo 6y ago> No comparison without explicit casts is a valid design choice. Sure, but that wasn't the claim.
- cygx 6y agoYeah, there was some interpretation of the intent behind the comment on my part (cf "you probably want it to be a static type error"). How you view the claim itself depends on your thoughts about the level at which equality should operate (should type tags be considered part of a value's identity, is it about the bit representation, or the abstract value encoded by that representation, ...)
- nonameiguess 6y agoYep. This is what I meant. I don't want to throw a runtime error. I want the type checker to be able to actually type check this statically, which mypy can't do.