4 ms·
Did not know about functools.singledispatchmethod, this could lead to some clean code in specific situations. I know I’ve missed overloading a few times!
by rolobio 4y ago
Did not know about functools.singledispatchmethod, this could lead to some clean code in specific situations. I know I’ve missed overloading a few times!
- mumblemumble 4y agoI've been making extensive use of it lately; it's treating me quite well.
- tonyg 4y ago`singledispatchmethod` definitely looks useful. The name isn't great, though. It actually offers double dispatch, not single dispatch! `divider.divide(10, 2)` first dispatches on `divider`, then on `10`. As so often with Python, I'm left wondering why they didn't follow through and properly complete the design, in this case perhaps offering multiple dispatch (multimethods) instead of just double dispatch. Casting an eye over the functools code, it looks like they have all the necessary C3 infrastructure in there.
- formerly_proven 4y agoPython sort of has multimethods, but only for type-annotations, not for actually dispatching to code.
- isoprophlex 4y agoDefinitely useful. That code looks ugly as fuck though
- make3 4y agothis feels really unpythonic, would be very surprised if I saw this in code
- kzrdude 4y agoFor a property setter, you have to give the method the same name as the original property, otherwise it mysteriously breaks. Here for singledispatchmethod they give it the name _. Why no consistency? Such things seem ad-hoc in python. (This criticism comes from an avid Python user.)
- ssl232 4y agoI guess to indicate that the method the @mydispatch.register() decorator wraps will not be added to the class namespace; it will only be accessible via the function wrapped by @singledispatchmethod. As is typical in Python, an underscore indicates an anonymous/unused name.
- kzrdude 4y agoThis explanation doesn't seem to cover the case with @property def foo(self) and the following @foo.setter def foo(self, value) - I wonder why the name of the foo.setter method matters, it doesn't make sense to me.
- ris 4y agoThough I'm guessing it won't get as much use now pattern matching has arrived and is a more general way of achieving the same thing.