Simply Jonathan

This is Simply Jonathan, online writing habitat for Jonathan Holst. In here, you may find content divided into three main categories: links, notes and essays. The links are to external content of interest; the notes are small thoughts and ponderings; the essays are longer, more thought-through entries, often debating a subject thoroughly. Read more about Jonathan and this site.

Better Url Handling for web.py

8 February 2007, 9:14 PM CET +0100

In my post about web.py I touched upon the fact that I don’t like web.py’s way of defining URL’s, that I find it too loose. Well, it’s a minor problem, but rather trivial to solve, so I did. As quoted in the original post, there is a bit more typing, but I personally prefer this solution. (To be fair, the example I gave in the original post can be applied to this code as well, but I’d say this makes it a tiny bit more readable):

def webpyurl(_tuple):
    """
    Map a structured tuple to a url that web.py will accept.

    Turns a tuple of the format 
    (
        ('a', 'b'), 
        ('c', 'd')
    ) 
    into 
    (
        'a', 'b', 
        'c', 'd'
    )

    Rather simple, but can make a huge difference in readability.

    @require enhancedappend()
    """

    thislist = []

    for (a,b) in _tuple:
        enhancedappend(thislist, a, b)

    return tuple(thislist)

def enhancedappend(_list, *appends):
    """
    list.append only takes 1 argument, this allows for more to be added
    """

    for append in appends:
        _list.append(append)

This code is also available on pyhacker.