Essential Coding Style Guidelines Every Python Developer Should Know | by Vinicius Monteiro | Feb, 2022

Write better Python code by applying the correct format for line indentation, line wrap, blank lines, whitespace, naming comments, and docstring

Vinicius Monteiro
Image by the author. Python logo downloaded from Python.org.

All programming languages ​​have strict formatting rules. If you don’t follow them, the code fails to execute.

For instance, in Java, the if statement must contain parentheses,if (x==true). In Python, a function must start with the word “def”, def cool_function(param): And so on.

However, some parts are left for software developers to decide how to write that doesn’t affect the execution.

For example, I prefer having a whitespace space surrounding the equals sign when assigning a value, x = 1. But I can write the code without whitespace, x=1and it will run as normal.

To avoid inconsistencies in the code and make it more readable, programmers are advised to follow coding format guidelines. According to official Python documentation, let’s look at some of the conventions in Python.

There are more essential recommendations. You should read the style guide for more details.

Guideline: 4 spaces per indentation level.

Languages ​​such as Java also has conventions for indentation. But in Python, the guidelines have more weight, as in some cases, the program fails to run if the indentation is incorrect.

Example of code using the right indentation level,

def day_of_week (day):
match day:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case 4 | 5 | 6:
return "Another day of the week"
case _:
return "Invalid day"

In the code above, there are 4 spaces between the margin (where defbegins) and the start of the line match day:. the line, case 1: is indented 4 spaces from the line above.

When 4 spaces per indentation level do not apply

  1. Add extra 4 spaces to distinguish function parameters from the function body. The first line inside the function should be indented to 4 spaces.
  2. Align the rest of the function parameters with those defined in the line above — it may require more than 4 spaces.
  3. If the line ends with function opening brackets, the line below can be indented to other than 4 spaces.
1. def cool_function(
param_a, param_b,
param_c, param_d):
print(var_one)
2. var = cool_function(param_a, param_b,
param_c, param_d)
3. result = cool_function(
param_a, param_b,
param_c, param_d)

Lines should be limited to 79 characters. When it’s a docstring or comments, it should be limited to 72 characters.

As a comparison, the convention for Java code is to limit the line to no more than 80 characters.

Such line length limitation in programming languages ​​makes the code more readable when you want to view multiple files side-by-side.

For top-level function and class definitions, two blank lines are advised. For method definitions inside a class, one blank line is recommended.

For instance,

import library1
import library2
import library3
def function1():
pass
def function2():
pass
class Class(object):

def method1():
pass

def method2():
pass

Should you have spaces or not around an operator?

For instance, i = i + 1 or i=i+1 ?

Here are some of the guidelines described in PEP 8,

  • Avoid spaces inside parentheses, brackets or braces. Correct: function(arg[1], {arg: 2})
  • Avoid spaces after a trailing comma and right before a closing parenthesis. Correct: var =(0,)
  • Avoid spaces before a comma, semicolon or colon. Correct: if x > 3: print(x)
  • Always surround binary operators with a single space, except when assigning a default value. Correct statements: i = i + 1 ;def cool(x=1)
  • Don’t try to align assignments by adding multiple whitespaces.

The naming style guideline depends on whether it is a class, module, function, variable, etc.

Package and modules

Package and module names should be short and all lowercase.

There are cases that an underscore _ can be used for module names, but the underscore _ symbol should be avoided for package names.

Classes

In general, classes should be in CamelCase format. For instance, class CarWash

Type variables

Type variables should usually use CamelCase format and preferably short names. The suffixes _co and _contra should declare covariant or contravariant behaviour.

Code below extracted from the Python documentation,

from typing import TypeVar

VT_co = TypeVar('VT_co', covariant=True)
KT_contra = TypeVar('KT_contra', contravariant=True)

Exceptions

The same convention as classes applies — CamelCase. If the exception is an error, the suffix Error should be added. For instance, IntegrityError .

Functions and variables

Functions and variables should be named lowercase, with words separated by underscore _. Example: def cool_function():

Avoid ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as a one-character variable name.

Function and method arguments

self for the first argument to instance methods.cls for the first argument to class methods.

Append an underscore or choose a synonym if the name clash with a keyword — do not abbreviate or change the spelling. Correct: class_; Incorrect: clss

Method and instance variables

Function naming rules apply—all lowercase, with words separated by an underscore.

Add a leading underscore for all private methods and instance variables. Example: _private_var

Two leading underscores can be used to avoid collision with subclasses. Python converts __cool_name declared in class MyClass, to _MyClass__cool_name .

This way, one cannot access the variable with MyClass.__cool_name. The variable is more private than a private variable that uses only one leading underscore.

Global variables

Like functions, global variables should be named all lowercase, with words separated by underscore _. Example, my_global_variable

Constants

Constants should be all capital, with words separated by an underscore. Example: MY_CONSTANT

Comment lines in Python start with a hash (#) symbol and should follow as below.

  • It’s better if the comments are in a line of their own.
  • Comments should be complete sentences.
  • Each sentence must end with a period.
  • Each sentence first word must start with an uppercase letter.
  • Two spaces must be used between sentences.
  • Comments must be written in English unless you’re sure only non-English speakers will read the code.

It’s not much different from the way we write regular text, except for the two spaces advised between sentences.

Block comments

Unlike Java and other programming languages, Python requires # before each comment line. It’s not possible to do the following,

/*
comment line 1
comment line 2
*/

The correct way of doing it is,

# comment line 1
# comment line 2

Note that there is a space after # . You should add this space.

Inline comments

Inline comments are when the comment is at the same line as the code statement.

def cool_function(x, y)    # comment line

You should limit the usage of this type of comment. It can be distracting.

“Docstring” is short for documentation strings. They are similar to comments but have a different purpose and format. Any text enclosed in triple-double quotes is interpreted as docstrings.

Here are the guidelines,

  • Docstrings should be added for all public modules, functions, classes and methods.
  • One-line docstrings should have all three closing double quotes in the same line.
  • No blank line before or after one-line docstrings.
  • For multi-line docstrings, all three closing double quotes should be in a separate line.
  • Docstrings should be in command format (Return this). It shouldn’t describe what the code does (Returns the day of the week).

Examples of docstrings,

"""Return first line of multi-line docstring 

All three closing double quotes in a line below.
"""

"""one-line documentation string"""

Consistency and good readability are the two key reasons why coding conventions exist. However, there are other aspects to consider.

Sometimes, programming language style guides should not be too rigidly followed. As advised in the documentation, these are some of the reasons to ignore a specific guideline (the last one is the most important),

When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.

To be consistent with surrounding code that also breaks it (maybe for historic reasons) — although this is also an opportunity to clean up someone else’s mess (in true XP style).

Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.

When the code needs to remain compatible with older versions of Python that don’t support the feature recommended by the style guide.

In general, if your application doesn’t fall into the categories above, it’s better to apply the coding style recommendations.

Thanks for reading.

Leave a Comment