Importance of style

Published

2023-08-01

The importance of style

As we learn to write programs, we will also learn how to use good style. Good coding style is more important than many beginners realize. Using good style:

  • helps you read your code more quickly and accurately.
  • makes it easier to identify syntax errors and common bugs.
  • helps clarify your reasoning about your code.

Most workplaces and open-source projects require conformance to a coding standard. For example, Google’s style guide for Python.1

When we’re solving problems we don’t want reading code or making decisions about formatting our code to consume more than their share of valuable cognitive load. So start off on the right foot and use good style from the beginning. That way, you can free your brain to solve problems—that’s the fun part.

Every language has its conventions, and you should stick to them. This is part of writing readable, idiomatic code.

PEP 8

Fortunately, there is a long-standing, comprehensive style guide for Python called PEP 8.2 The entire style guide PEP 8 – Style Guide for Python Code is available online3. Noted Python developer Kenneth Reitz has made a somewhat prettified version at https://pep8.org/. You should consult these resources for a complete guide to good style for Python. Many projects in industry and in the open source world enforce the use of this standard.

Don’t think in terms of saving keystrokes—follow the style guide, and you’ll find this helps you (and others!) read and understand what you write.

Whitespace

Yes! Whitespace is important! Using whitespace correctly can make your code much more readable.

Use whitespace between operators and after commas.4 Example:

# Don't do this

x=3.4*y+9-17/2

joules=(kg*m**2)/(sec**2)

amount=priceperitem*items

Instead, do this:

# Better

x = 3.4 * y + 9 - 17 / 2

joules = (kg * m ** 2) / (sec ** 2)

amount = price_per_item * items

Without the whitespace between operators, your eye and brain have to do much more work to divide these up for reading.

Sometimes, however, extra whitespace is unnecessary or may even hinder readability. You should avoid unnecessary whitespace before closing and after opening braces, brackets or parentheses.

# Don't do this

picas = inches_to_picas ( inches )

# Better

picas = inches_to_picas(inches)

Do not put whitespace after names of functions.

# Don't do this

def inches_to_points (in):
    return in * POINTS_PER_INCH

# Better

def inches_to_points(in):
    return in * POINTS_PER_INCH

In doing this, we create a tight visual association between the name of a function and its parameters.

Do not put whitespace before commas or colons.

# Don't do this

lst = [3  ,  2  ,  1]

# Better
lst = [3, 2, 1]

It’s OK to slip a blank line within a block of code to logically separate elements but don’t use more than one blank line. Exceptions to this are function declarations which should be preceded by two blank lines, and function bodies which should be followed by two blank lines.

Names (identifiers)

Choosing good names is crucial in producing readable code. Use meaningful names when defining variables, constants, and functions. This makes your code easier to read and easier to debug!

Examples of good variable names:

  • velocity
  • average_score
  • watts

Examples of bad variable names:

  • q
  • m7
  • rsolln

Compare these with the good names (above). With a good name, you know what the variable represents. With these bad names, who knows what they mean? (Seriously, what the heck is rsolln?)

There are some particularly bad names that should be avoided no matter what. Never use the letter ”O” (upper or lower case) or ”l” (lowercase ”L”) or ”I” (upper case ”i”) as a variable name. “O” and “o” look too much like “0”. “l” and “I” look too much like “1”.

While single letter variable names are, in general, to be avoided, it’s OK sometimes (depending on context). For example, it’s common practice to use i, j, etc. for loop indices (we’ll get to loops later) and x, y, z for spatial coordinates, but only use such short names when it is 100% clear from context what these represent.

Similar rules apply to functions. Examples of bad function names:

  • i2m()
  • sd()

Examples of good function names:

  • inches_to_meters()
  • standard_deviation()

ALL_CAPS, lowercase, snake_case, camelCase, WordCaps

In Python, the convention for naming variables and function is that they should use lowercase or so-called snake case, in which words are separated by underscores.

In some other languages, camelCase (with capital letters in the middle) or WordCaps (where each word is capitalized) are the norm. Not so with Python. camelCase should be avoided (always). WordCaps are appropriate for class names (a feature of object-oriented programming—something that’s not presented in this text).

  • Good: price_per_item

  • Bad: Priceperitem or pricePerItem

As noted earlier, ALL_CAPS is reserved for constants.

Line length

PEP 8 suggests that lines should not exceed 79 characters in length. There are several reasons why this is a good practice.

  • It makes it feasible to print source code on paper or to view without truncation on various source code hosting websites (for example, GitHub, GitLab, etc.).
  • It accommodates viewports (editor windows, etc.) of varying width (don’t forget you may be collaborating with others).
  • Even if you have a wide monitor, and can fit long lines in your viewport, long lines slow your reading down. This is well documented. If your eye has to scan too great a distance to find the beginning of the next line, readability suffers.

Throughout this text, you may notice some techniques used to keep line length in code samples within these bounds.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).

Footnotes

  1. https://google.github.io/styleguide/pyguide.html↩︎

  2. PEP is short for Python Enhancement Proposal↩︎

  3. https://peps.python.org/pep-0008/↩︎

  4. One exception to this rule is keyword arguments in function calls, for example, the end keyword argument for the built-in print() function.↩︎