2 ms·
Huh? But that's not single dispatch? Single dispatch is deciding what function to call based on the type of your object, not on the type of arguments. That's ca
by revelation 13y ago
Huh? But that's not single dispatch? Single dispatch is deciding what function to call based on the type of your object, not on the type of arguments. That's called double dispatch.
Single dispatch is pretty standard polymorphism, C++ can do that.
- pixelmonkey 13y agoThat's a bit of a semantic argument. Python already has "object-oriented single dispatch" -- aka traditional object-oriented polymorphism. What this module adds is "functional single dispatch". So, whereas before you'd always be forced to implement some type-varying function using two classes `HandleA` and `HandleB`, each with an implementation for `handle`: class HandleA: def handle(self): pass class HandleB: def handle(self): pass def main(obj): # obj could be instance of HandleA or HandleB obj.handle() In this case, "dynamic dispatch" is done by `obj.handle()`, which will pick a different implementation depending on the type of obj. With this PEP/stdlib addition, you can now write two functions, `handle_A` and `handle_B`, which take an argument, `obj`, and are dynamically dispatched using the generic function `handle`. from functools import singledispatch @singledispatch def handle(obj): pass @handle.register(A) def handle_A(obj): pass @handle.register(B) def handle_B(obj): pass def main(obj): # obj could be instance of A or B handle(obj) And in this case, "dynamic dispatch" is done by `handle(obj)`, or really, by the dispatcher decorator. It chooses `handle_A` or `handle_B` based on the type of the `obj` argument The reason this is a nice addition is because it makes Python eminently "multi-paradigm" -- you can choose object-oriented or functional styles depending on your taste and the applicability to the task at hand, instead of being forced into one programming style or the other. (the content of my comments got long enough that I decided to document them for posterity over on my blog: http://www.pixelmonkey.org/2013/10/20/singledispatch http://www.pixelmonkey.org/2013/10/20/singledispatch)