Five-minute Multimethods in Python

submited by
Style Pass
2021-07-09 15:30:06

So what are multimethods? I'll give you my own definition, as I've come to understand them: a function that has multiple versions, distinguished by the type of the arguments. (Some people go beyond this and also allow versions distinguished by the value of the arguments; I'm not addressing this here.)

As a very simple example, let's suppose we have a function that we want to define for two ints, two floats, or two strings. Of course, we could define it as follows: def foo(a, b): if isinstance(a, int) and isinstance(b, int): ...code for two ints... elif isinstance(a, float) and isinstance(b, float): ...code for two floats... elif isinstance(a, str) and isinstance(b, str): ...code for two strings... else: raise TypeError("unsupported argument types (%s, %s)" % (type(a), type(b)))

But this pattern gets tedious. (It also isn't very OO, but then, neither are multimethods, despite the name, IMO.) So what could this look like using multimethod dispatch? Decorators are a good match: from mm import multimethod @multimethod(int, int) def foo(a, b): ...code for two ints... @multimethod(float, float): def foo(a, b): ...code for two floats... @multimethod(str, str): def foo(a, b): ...code for two strings...

Leave a Comment