Sunday, September 27, 2015

Flattening Python Code with "continue"

Flat code is better than nested.  It's more readable, easier to update, and easier to debug.  All of the linux kernel source code uses 8-space indents because, as I've seen it explained by Linus, if you can't use enough indents with 8-space, you have too many indents and need to refactor your code so it's more simple.

I do some data analysis type stuff at work fairly often.  Sometimes I'll have a half-dozen conditional statements to satisfy in a loop where I'm ticking over rows of data.  Using the "continue" statement is a really simple way to keep code flat and manageable.

Bad form would be like this:
for row in my_data:
    if row[val] == 'blah':
        if row[val2] == 'test':
            doFunc(row)
            doFunc2(row[val3])
            if row[val3]:
                yield row


Better would be like this:
for row in my_data:
    if row[val] != 'blah':
        continue
    if row[val2] != 'test':
       continue
    doFunc(row)
    doFunc2(row[val3])
    if row[val3]:
        yield row

No comments: