Single dispatch in Python

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

Andrew Montalenti describes the almost-multimethods that Python got in 3.4:

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)

I dislike the fact that this is implemented using “@”, which is used for annotations in most of the languages that I’m aware of, but otherwise I am pleased to see something this close to multimethods (I’ve become a fan of multimethods in Clojure).

But about this:

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.

Python is multi-paradigm, but its basic types are a strange mix of mutable and immutable. Strings and tuples are immutable, lists are mutable, etc. There is a cost of being multi-paradigm: you may not get the benefits of a particular paradigm. A pure functional language defaults to immutable in everything. If you have to work around mutable variables while trying to imitate the functional style, then the style is imposing extra work on you, rather than saving you work.

Having said that, I acknowledge that you can implement anything in any language. There are people now doing functional programming in Javascript, even though Javascript is mutable in every imaginable way. Given enough meta-programming, you can create libraries that, for all practical purposes, create a new language where you can work with just 1 paradigm.

Also, when I read the official docs, I see:

Data attributes may be referenced by methods as well as by ordinary users (“clients”) of an object. In other words, classes are not usable to implement pure abstract data types. In fact, nothing in Python makes it possible to enforce data hiding — it is all based upon convention.

That must make it somewhat difficult to implement some object oriented patterns? Although Luciano Ramalho says descriptors can give us the encapsulation we might want.

Post external references

  1. 1
    http://www.pixelmonkey.org/2013/10/20/singledispatch
  2. 2
    https://docs.python.org/2/tutorial/classes.html
  3. 3
    http://pyvideo.org/video/1760/encapsulation-with-descriptors
Source