Pattern Matching in Python

I have loved Pattern Matching since the day I learned about it (First in Erlang, then Haskell).

So it was quite natural that I will take a stab at porting it to Python. It was a slow day at office today and while browsing the webs I came across this little hack from Guido himself on multi-methods.



Reading the article got me thinking about Pattern Matching again, and given that I had some spare time, I decided to take a plunge.



Guido’s idea is quite simple, he creates a wrapper for functions and registers each of them in a global registry. In addition to the function, he also provides each wrapper with its own set of arguments (Types of the wrapped function arguments) and then uses this to decide which function to call on runtime (based on the types of arguments used to call). Below is a Bunk containing Guido’s code and a few examples. Click Run too see the output.





My approach is almost the same except that when the function is called I match each argument passed to the function to the corresponding one in the decorator and call the first function which matches on all arguments. Take a look at the code (Click Run for output).

Of course this is just a dirty dirty hack, lots of limitations, and just bad overall. Python can be abused so easily and this is a case in point. :)