Multiple dispatch for comparison operators?
The way I understand it, multiple dispatch is programming language feature wehreby a function or method overload is chosen based on run time types. Python already has single dispatch (functools.singledispatch). It also has the concept of overloads for type annotations (typing.overload). My main motivation for suggesting multiple dispatch for Python is to simplify writing comparison operators and to facilitate mypy's ability to understand them. Python has a long history of writing comparison operators like this: class X: def __lt__(self, other: Any) -> bool: if isinstance(other, X): return self.a < other.a return NotImplemented Thanks to modern type annotations, multiple dispatch could allow something like this: def __lt__(lhs: X, rhs: X) -> bool: return lhs.a < rhs.a Essentially, in most cases of implementing comparison operators, the user implements the dispatching with a little help from the interpreter thanks to "return NotImplemented". One benefit of double dispatch would be addressing typing annotation problems like this: https://github.com/numpy/numpy/issues/17368. A type checker cannot know the return type of the comparison operators. Even in general, a type checker can't know whether two types are comparable. Multiple dispatch is one of Julia's main selling points compared with Python. They make some convincing arguments here: https://www.youtube.com/watch?v=kc9HwsxE1OY. What I'm wondering is whether there's any possibility in Python's distant future for implementing comparison operators using double dispatch? Besides being simpler, type checkers like mypy would have an easier time inferring types. The major drawback is backwards compatibility. Is there a way to craft things so that old style comparison operators could co-exist with new style ones? Best, Neil
participants (1)
-
Neil Girdhar