One of the core values of Python is readability.
To encourage this value it has a set of guidelines on how to format your code called PEP 8. Most of these points are applicable to all languages, so even if you aren’t blessed to use Python you still might want to check it out.
One of the PEP 8 rules is lines shouldn’t be longer than 79 characters. This is also a rule in typography. That’s the length of line that doesn’t require extra mental effort to move back to the beginning of the next line.
Much of this post and the next one are from a talk by Brandon Rhodes entitled A Python Aesthetic: Beauty and Why I Python and available on YouTube. It got me inspired to think about this stuff again and motivated to make these posts.
Here’s a few of tips on how to shorten lines effectively.
Shorten Lines By Adding Variables
As Mr. Rhodes pointed out in the source video, it’s a feature of math that you can assign some part of an operation to a variable and use that to pass on to another operation. Why do programmers seem to want to avoid this?
I don’t know, probably because programmers are lazy. Well some programmers. The same kind of programs that use one character variable names and magic numbers.
But not you right?
Example:
canvas.drawString(x, y, ‘Please press {}’.format(key))
Our first thought is using return to shorten.
canvas.drawString(x, y, ‘Please press {}’.format(key))
But if it has to be two lines anyway….
message = ‘Please press {}’.format(key) canvas.drawString(x, y, message)
Adding the message variable not only shortens the line, it gives us a variable that tells us what it is. The message is now easily changed, printed for debugging or logged later.
Shortening Long Formulas
Sometimes you have a big mathematical formula that stretches past 79 characters. Especially if you use good variable names. Here Mr. Rhodes disagrees with PEP 8 and I agree with him.
Example:
adjusted_income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deductions - student_loan_interest)
PEP-8 says to divide binary operations after the operator. This is bad.
PEP-8 badness:
adjusted_income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deductions - student_loan_interest)
Donald Knuth says divide before the operator.
Knuth Goodness:
adjusted_income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deductions - student_loan_interest)
This seems much clearer, and put the operators front and center. Subtractions actually look like the variable is negative.
Image: Photographer Ron Davis (Me). Model Virginia McConnell.