Sunday, 21 August 2011

Expressiveness in Python

I've been having fun reworking the Literate Programming tool nuweb in Python; the Mercurial repository for the rework can be browsed here. On the way I've come across a neat hack, and a rather unlikely workaround for Python's lack of a switch statement.

List comprehension

List comprehensions are described in the Python documentation.

They let you replace this:

result = []
for k in sorted(matches.keys()):
    result.append([k, matches[k]])
return result

which takes the dictionary matches, sorts the keys, and generates a list of lists, where the internal lists contain the key and its associated value by this:

return [[k, matches[k]] for k in sorted(matches.keys())]

which is very expressive after you've seen it a few times. Apparently you can nest list comprehensions, if you have the stomach for it.

No switches

You'd normally use a switch to implement this factory function, which returns an Index of whatever kind the user asked for.

def factory(id):
    """Creates and returns the appropriate type of Index for
    return {
        'f' : lambda: FileIndex(),
        'm' : lambda: MacroIndex(),
        'u' : lambda: IdentifierIndex()

I can't help thinking that using a nonce dictionary of lambda functions for this is going a bit far!

No comments:

Post a Comment