Have you ever written a little one or two line snippet of code you were super proud because it was oh so short and sneaky and clever? But then, like a month (or 20 mins) later, you have to go back to it and you have no idea what that stinker’s actually doing? Yeah, me neither.

I have some thoughts on little clever bits of code. First of all, they’re cool. Yay for figuring out how to compress say 15 lines into two! Second of all, they can drive me nuts when having to go back to review old code. Especially if it contains regex (shakes fist at regex). I also think that there are sometimes places that are more suited for the clever bits than others. Let me explain . . .
I think that if you’re deliberately trying to condense your work down into fewer lines for the sole sake of fewer lines, you’re in danger of losing the overall clarity of you code. And in the long run, that’s going to make your code more difficult to maintain by you and others.
Now when do I think that a cute one-liner is appropriate? I like to use them when doing so doesn’t distract from the overall idea of the function or method I’m writing. It’s like a mini subroutine (but not) that I don’t have to do any extra work for. For example:
# x is a datetime field
sorted(my_list, key=lambda x:x[1], reverse=True)
I could have written a helper function that went through my list and sorted them by date then reversed it, but it turned out to be much more concise to use a lambda function within the built-in sorted() function. It also made way more sense to just use a built in function rather than writing my own.
Another example:
# _ can be used in python editor to reference whatever
# was on the previous line. Fun, right?
>>> [1, 23, 1, 45, 5, 9]
[1, 23, 1, 45, 5, 9]
>>> [s for s in _ if s > 10]
[23, 45]
# The following is equivalent to above
# but in more lines.
foo = [1, 23, 1, 45, 5, 9]
foo2 = []
>>> for each in foo:
... if each > 10:
... foo2.append(each)
...
>>> foo2
[23, 45]
But if that logic was more complex and my one liner started getting long and I had to start line wrapping it to fit? Nope, that’s going to be way more difficult to read and understand in the long run. (That also goes against the PEP 8 Style Guide. I like to stay within the 72 character line limit, thank you.) Anyone coming after you that has to do anything with that code (including you) is just going to want to whack you over the head with a boot. Just write out some loops, man.
Have fun finding clever ways of coding!
-Rachel

