The Artima Developer Community
Sponsored Link

Python Buzz Forum
Lexical Dispatch in Python

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Thomas Guest

Posts: 236
Nickname: tag
Registered: Nov, 2004

Thomas Guest likes dynamic languages.
Lexical Dispatch in Python Posted: Feb 9, 2008 10:05 PM
Reply to this message Reply

This post originated from an RSS feed registered with Python Buzz by Thomas Guest.
Original Post: Lexical Dispatch in Python
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
Latest Python Buzz Posts
Latest Python Buzz Posts by Thomas Guest
Latest Posts From Word Aligned: Category Python

Advertisement

A recent article on Ikke’s blog shows how to emulate a C switch statement using Python. (I’ve adapted the code slightly for the purposes of this note).

def handle_one():
    return 'one'

def handle_two():
    return 'two'

def handle_three():
    return 'three'

def handle_default():
    return 'unknown'

cases = dict(one=handle_one,
             two=handle_two,
             three=handle_three)

for i in 'one', 'two', 'three', 'four':
    handler = cases.get(i, handle_default)
    print handler()

Here the cases dict maps strings to functions and the “switch” is a simple matter of looking up and dispatching to the correct function. This is good idiomatic Python code. When run, it outputs:

one
two
three
unknown

Here’s an alternative technique which I’ve sometimes found useful. Rather than build an explicit cases dict, we can just use one of the dicts lurking behind the scenes — in this case the one supplied by the built-in globals() function.

Leaving the handle_*() functions as before, we could write:

for i in 'one', 'two', 'three', 'four':
    handler = globals().get('handle_%s' % i, handle_default)
    print handler()

Here, globals() returns us a dict which maps names in the current scope to their values, and since our handler functions are uniformly named, we can combine some string formatting with a simple dictionary look-up to get the required function.

A warning: this is unusual and non-idiomatic code, and in this particular case, the original explicit dictionary dispatch would be better. In other situations though, when the scope narrows to a class or a module, it may well be worth remembering that classes and modules behave like dicts which map names to values. The built-in getattr() function can then be used as a function dispatcher. Here’s a class-based example:

Sketch of an XHTML paragraph formatting class
PLAIN, BOLD, LINK, DATE = 'PLAIN BOLD LINK DATE'.split()

class Paragraph(object):
    def __init__(self):
        self.text_so_far = ''

def __str__(self):
        return self._do_tag(self.text_so_far, 'p')

def _do_tag(self, text, tag):
        return '<%s>%s</%s>' % (tag, text, tag)

def do_bold(self, text):
        return self._do_tag(text, 'b')

def do_link(self, text):
        return '<a href="%s">%s</a>' % (text, text)

def do_plain(self, text):
        return text

def append(self, text, markup=PLAIN):
        handler = getattr(self, 'do_%s' % markup.lower())
        self.text_so_far += handler(text)
        return self

Maybe not the most fully-formed of classes, but I hope you get the idea! Incidentally, append() returns a reference to self so clients can chain calls together.

>>> print Paragraph().append("Word Aligned", BOLD
...                 ).append(" is at "
...                 ).append("http://wordaligned.org", LINK)
<p><b>Word Aligned</b> is at <a href="http://wordaligned.org">http://wordaligned.org</a></p>

Read: Lexical Dispatch in Python

Topic: A Simple CMS Previous Topic   Next Topic Topic: The great effects of little imperfections

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use