May 11, 2004
Just a Little Better Every Day

For some reason, I seem recently to have needed to code a number of functions which take a list of strings as an argument:

setText(aWindow, ['a line', 'another line'])

You often need to pass only one string in, though, and I coded my functions such that you could do this in a 'natural' way:

setText(aWindow, 'just one line this time')

I coded this as follows:

def setText(window, text, append=False):
    # Ensure that text is a list
    try:
        text + ''
        text = [text]
    except TypeError:
        pass

    # Rest of funtion, which can assume that 'text' is a list of strings

Robin Munn suggested an improvement to this:

    try:
        text + ''
    except TypeError:
        pass
    else:
        test = [text]

Nice. In my version, I'd have a problem in the (unlikely, but not impossible) case of test = [text] throwing a TypeError.

It's not a huge improvement, true, but I like it. A day in which I learn to improve is a day not wasted.

Posted to Python by Simon Brunning at May 11, 2004 01:01 PM
Comments
Post a comment
Name:


Email Address:


URL:



Comments:


Remember info?