Python Generic Dispatch?

2010-06-25 22:30:17-0400 - python (2) - 38 comments

My friend Kyle and I were discussing the nice generic dispatch system in Haskell, and how it makes function definitions nice. I mentioned it would be nice to pull that syntax into Python, and an hour later here I am. I have implemented a very rough solution on github (VIEW SOURCE).

Solution Looking for a Problem

So I know this may be a solution looking for a problem, but I’m really happy that by abusing the inspect system of python and using decorators you can write such a system in a concise way. The basic idea is that I’ve implemented a decorator called dispatch. This decorator takes arguments which defined a kind of signature for the function. This system is actually very close to method overloading in Java or function overloading in C. However, you can take it further (much further). The dispatcher can actually take types, predicate functions, values, or lists! We can take the simplest case, values and implement Fibonacci with it:

# inside returns predicate that's predefined
@dispatch(inside(0, 1))
def fib(n):
    return n

@dispatch(int)
def fib(n):
    return fib(n - 1) + fib(n - 2)

>>> fib(6)
13

Now I would never, ever suggest writing a Fibonacci like this, but this just provides an example as to how this may work. Now, here comes the part that’s interesting. Because of the dynamic dispatch nature of this, we can add to this if we need to for later programs. As an example, suppose I want to come up with a fast version of fib for longs. We can just add this:

from mymodule import fib

@dispatch(long)
def fib(n):
    # Faster fib implementation
    a, b = 1, 0
    c, d = 0, 1
    while i > 0:
        if i % 2:
            c, d =  a * (c + d) + b * c, a * c + b * d
            i -= 1
        i >>= 1
        a, b =  a ** 2 + ((a * b) << 1), a ** 2 + b ** 2
    return c

>>> fib(26L) # much faster!
196418

Or let’s say that we want to take strings as an input, we can also add:

@dispatch(basestring)
def fib(n):
    return fib(long(n))

>>> fib('26')
196418

And now each time we do this we update the local scope to have the new function. There is no magic monkey patching done, so if you want to do this you have to create your own global registry. I like this because it means that by default you will branch off and create different versions of the function if you have more than one module. I believe this is what you’d expect if you understood scoping etc.

Deeper Down the Rabbit Hole

We aren’t quite finished, are we? Because we also want to be able to take lists of objects (or I do). Let’s say that I have a function that dumps data but specifically based on what is in the data. Here’s a quick example:

# Generic default
@dispatch()
def dumper(data):
    import pprint
    pprint.pprint(data)

# Now special if the list contains a single dict and another value.
@dispatch([anything, dict]) # anything is a predicate function predefined
def dumper(data):
    print "Data for %s" % data[0]
    for key, value in data[1]:
        print "%s: %s" % (key, value)

Viola! The dispatcher will actually recurse down any list or iterable you have, so you can have @dispatch([anything, [anything], [[int]]]) if you wanted.

There’s one more trick not mentioned here, and that is that if you write a default case (@dispatch() with no specifications), then any further conditions defined later are actually inserted before this case. This allows me to write what I have above, since I have defined the default before the specific case. This would allow me to add other specialties to the function as the function warrants it.

Conclusion

I’m sure there’s plenty more to play with in this arena, and I’m actually somewhat surprised I was not able to find something like this already prepackaged for python. After playing with it for a little while I may put it up on pypi. Of course, the drawback is performance. For a recursive function like the naive fib, the dispatch version is 10x slower. However, for a lot of real-world cases, you aren’t wrapping a recursive function with this, so it may actually be useful.


Bookmark this entry: Slashdot Digg del.icio.us Newsvine Stumbleupon

Comments on This Post:

Posted by Kyle Miller

United States

on June 26, 2010

Actually, it was talk about a predicate dispatch system in Scheme, as well as Haskell's nice pattern dispatch system. Haskell would never make something like this to muddy its type system :-) Speaking of Haskell, I'd like to see those variable-binding predicates!

Reply To This Comment

Posted by Matt

United States

on June 26, 2010

Consider programming in ML? A way nicer and faster implementation of this sort of thing...

Reply To This Comment

Posted by banister

New Zealand

on June 26, 2010

C doesn't support function overloading :)

Reply To This Comment

Posted by Bertrand Croq

France

on June 26, 2010

take a look at peak.rules http://peak.telecommunity.com/DevCenter/RulesReadme

Reply To This Comment

Posted by Code Monkey

United States

on June 27, 2010

http://sourceforge.net/projects/pymultimethods/ Here's another person's implementation of this. I got this working with one of my projects, although I'm thrilled to see other programmers tackling this feature. I must say, there's a lesson here about doing it yourself: I loafed around and waited for others to do this for months.

Reply To This Comment

Posted by Ian Bicking

United States

on June 29, 2010

I played around with something like this too, though I was thinking about it in terms of Erlang: patmatch

peak.rules is definitely the most clever application of this, though maybe clever to a fault.

Reply To This Comment

Posted by tindzk

Germany

on July 12, 2010

banister: Actually, Clang has a language extension for function overloading in C. Even though the feature is quite unknown, it's already pretty stable. I'm using it in nearly all of my projects. :) Currently, the only downside is that you cannot use overloaded functions as pointers (there were some discussions about implementing it on the mailing list earlier this year though).

Reply To This Comment

Posted by Pyncdyncbok

Netherlands

on Jan. 15, 2011

In the seventh heaven New Year, everyone! :)

Reply To This Comment

Posted by cheallowl

Ukraine

on April 02, 2011

viagra without prescription http://trust-canadian.com/products/viagra.htm - 0.89$

Reply To This Comment

Posted by Accorkeme

China

on April 09, 2011

Excuse for that I interfere … To me this situation is familiar. Let's discuss.
zdjęcia ślubne Lodz

Reply To This Comment

Posted by Boosuretinten

China

on April 11, 2011

Posted by acai berry reviews uk

China

on April 14, 2011

A hug is like a boomerang - you get it back right away.

Reply To This Comment

Posted by arrareDug

Netherlands

on April 16, 2011

hi, visit my soft blog http://lobikota.blog.com/

Reply To This Comment

Posted by sms

on April 16, 2011

After reading this post, its my sincere feeling that you own the precise knoeledge of what are you deliberating.I seriously wish to congratulate you for your passion towards your work that has helped you stand today on this height.Genuinely,there has not been even once that I have visited your post and went without acquiring some good information.Get Going.And yes i have bookmarked your site mike.axiak.net .

Reply To This Comment

Posted by arrareDug

Netherlands

on April 18, 2011

hi, visit my soft blog http://qufecoup.blog.com/

Reply To This Comment

Posted by arrareDug

Netherlands

on April 21, 2011

Buy cheap Adobe Photoshop CS4 Extended Edition Oem Software Version Buy cheap Lavalys EVEREST Corporate Edition 5.30.1900 Oem Software Version Buy cheap Microsoft Office Visio Pro 2007 Oem Software Version Buy cheap Rosetta Stone Ltd Rosetta Stone British 3 levels 3.2 Oem Software Version Buy cheap Intervideo WinDVD Creator 2 Oem Software Version

online cheap MakeMusic in Tennessee

Reply To This Comment

Posted by arrareDug

Netherlands

on April 23, 2011

Buy cheap Acronis True Image Home 2011 Oem Software Version Buy cheap Rosetta Stone Ltd Rosetta German German 3 levels 3.2 Oem Software Version Buy cheap Adobe Illustrator CS4 Oem Software Version Buy cheap Steinberg Clean 3.0 Oem Software Version Buy cheap onOne Software FocalPoint 1.0 Oem Software Version

buy online Steinberg in Pennsylvania

Reply To This Comment

Posted by arrareDug

Netherlands

on April 25, 2011

Buy cheap Corel CorelDRAW Graphics Suite X5 Oem Software Version Buy cheap Mcafee SiteAdvisor with Web Search 2.9 Oem Software Version Buy cheap Pixarra TwistedBrush Pro Studio 16.24 Oem Software Version Buy cheap Kelby Introducing Adobe Configurator for Photoshop CS4 Oem Software Version Buy cheap TomTom map of USA, Canada & Mexico 8.55.2934 Oem Software Version

buying online Digital Audio in Tennessee

Reply To This Comment

Posted by arrareDug

Netherlands

on April 26, 2011

Buy cheap Adobe Premiere Elements 7.0 Oem Software Version Buy cheap Bigasoft iPad Video Converter 2.5.0.3947 Oem Software Version Buy cheap Bigasoft Avi Converter 2.5.0.3947 Oem Software Version Buy cheap Avanquest Fix-It Utilities 9 Portable Oem Software Version Buy cheap Graphisoft Mep Modeler 12.2327 Oem Software Version

buy online Nuance PaperPort Professional 12 in Hollywood

Reply To This Comment

Posted by casio digital camera

China

on May 24, 2011

Howdy! Do you resort to Twitter? I'd like to trail you if that would be ok. I'm beyond a enjoying your blog and look into the open to late posts.

Reply To This Comment

Posted by Buncgonosig

on May 31, 2011

Posted by Impussysync

on May 31, 2011

Posted by WphydayBak

Germany

on June 15, 2011

get 1000 facebook likes how to get 1000 facebook likes buy facebook likes

http://www.survivors-guild.com/smf/index.php?action=profile;u=336 http://kirelly.vel-apps.com/forum/index.php?action=profile;u=9588
how to get 1000 facebook likes buy facebook likes buy 1000 facebook likes get facebook likes


buy facebook likes how to get facebook likes buy 1000 facebook likes get facebook likes

Reply To This Comment

Posted by hp pavilion review

China

on June 16, 2011

Whoa! This blog looks accurately like my disused in unison! It's on a from start to finish other thesis but it has euphonious much the anyhow episode layout and design. Sterling choice of colors!

Reply To This Comment

Posted by obozy

China

on June 24, 2011

You can certainly see your skills in the work you write. The world hopes for even more passionate writers like you who are not afraid to say how they believe. Always go after your heart.
obozy młodzieżowe

Reply To This Comment

Posted by ssoasualty

Germany

on June 30, 2011

iphone unlock unlock iphone

unlock iphone unlock iphone unlock iphone
how to unlock iphone

how to unlock iphone unlock iphone unlock iphone how to unlock iphone

Reply To This Comment

Posted by LewReapse

Russian Federation

on July 06, 2011

основні засади грошово кредитної політики смотреть русские инцест фильмы транссексуалы порно секс онлайн сосет хуй видео смотреть первое русское порно онлайн сотреть порно ролики онлайн бесплатно стр 674

Reply To This Comment

Posted by unresygiedide

Russian Federation

on July 08, 2011

фильм порно большой анна семенович без лифчика голая
букаке скачать большие сиськи порно онлайн бесплатные порно фильмы инцест запрещённое порновидео смотреть онлайн

Reply To This Comment

Posted by SEO_master

United States

on July 13, 2011

Cenik SEO optimalizace webu http://www.zpetneodkazy-linkbuilding.com/cenik-zpetnych-odkazu-seo-optimalizace-analyza-klicovych-slov/ SEO servis za zajimavou cenu.

Reply To This Comment

Posted by sphydayBak

Germany

on July 31, 2011

buy cheap facebook fans buy facebook fans cheap buy facebook likes

buy guaranteed facebook fans buy facebook likes buy cheap facebook fans buy likes on facebook


facebook likes buy buy facebook likes cheap buy facebook page likes buy guaranteed facebook fans

Reply To This Comment

Posted by Abril

Germany

on Aug. 01, 2011

You got great points there, so I always visit your site, it looks like you are an expert in this field. keep up the fantastic work, My friend recommends your site.

My blog:
credit rachat credit et comparateur Rachat de credit

Reply To This Comment

Posted by sphydayBak

Germany

on Aug. 23, 2011

buy bulk facebook fans buy cheap facebook fans buy facebook fans cheap

buy facebook likes cheap buy targeted facebook likes facebook likes buy buy targeted facebook likes


facebook likes buy buy facebook likes buy likes on facebook buy cheap facebook fans

Reply To This Comment

Posted by Amercerpef

Germany

on Sept. 03, 2011

http://www.newsarticleinsiders.com/how-to-unlock-iphone-4-effectively-in-just-minutes.html So I was surfing the internet like I usually do and suddenly Google Chrome shuts down. Now this program called "Antivirus Live" appears to have installed itself. Now as a limited user on this computer, I have no idea this program got in since I can't download anything anyway. I have gotten its counterpart, Antivirus 2008 before and successfully removed it as a limited user but this one is proving to be a challenge. And I do have security, Mcafee, but it falls short when removing malware. Would any of you happen to know how to get rid of this foul program using a limiter user account?

Reply To This Comment

Posted by buy facebook likes

on Nov. 12, 2011

nice article in my opinion Behind every fine Facebook traffic generation approach, could be the tough task of getting more Facebook likes on a regular basis. To make that happen, you need to always bear in mind that the primary aim needs to be of keeping your search limited, focusing on your Facebook likes properly, and getting the work done promptly will definetly try your tips mean while buying likes for my pages <a href="http://www.splib.com/">buy facebook likes</a> and it works great

Reply To This Comment

Posted by omiplilakig

on Jan. 22, 2012

http://google.com.ua - check8899
проститутки москвы цены http://rghost.ru/36040909 - Проститутки горада воронежа памятник проститутке в Амстердаме http://rghost.ru/36038859 - Сайт проституток в сша миньет в машине екатеринбург http://rghost.ru/36035343 - Проститутк львов контакти проститутки Питера.Искать по станциям метро http://rghost.ru/36037642 - Праститутки преображенская площадь интим досуг в тобольске http://rghost.ru/36043209 - Русская праститутки секс спб калининский http://rghost.ru/36036400 - Проститутки москвы в возрасте индивидуалки городов кемеровской области http://rghost.ru/36038998 - Адреса проституток спб проститутки питера 30 40 лет http://rghost.ru/36031800 - Шлюхи тамбов проститутки на васильевском ретро http://rghost.ru/36038601 - Транссексуалы пенза проститутки индивидуальные проститутки иркутск http://rghost.ru/36032237 - Трансвеститы молдовы

Reply To This Comment

Posted by Foenteecooppy

on Feb. 02, 2012

Hi! my identify is Jully. I would like to meemeet good urchin :)
This is my homepage - http://jskdh5jkd7djh4.com/l

Reply To This Comment

Reply to the original post