Python Coding Best Practices and Style Guidelines

Portrait of satisfied female with beautiful smile enjoying watching movie in silver computer and sitting in lotus pose on the floor over grey wall

You’ve spent hours studying Python, and you may even have several successful projects in your portfolio. But do you write your Python code like a pro? Let’s review some important guidelines to help you clean up your code.

What Is the Pythonic Way of Writing Code?

There are often several ways to do something in Python; naturally, some are better than others. But you should always prefer code that is not only syntactically correct but also in alignment with coding best practices and the way the language ought to be used.

Writing code in a Pythonic way implies following the official Style Guide for Python Code as well as choosing the most efficient option in terms of simplicity and readability of code.

Of course, reading through all the style guidelines could be boring. So, to make your life easier, I want to share with you the main ideas and the most important rules from the guide in a slightly more engaging and concise format. That doesn’t mean you shouldn’t read the guide, but this article will at least make your work a little easier.

How to Structure Python Code

Indentation

You should use four spaces per indentation level. Spaces, and not tabs, are the preferred indentation method in Python. Moreover, Python 3 doesn’t allow you to mix spaces and tabs for indentation. (Note: “Spaces versus tabs” is a bit of a contentious holy war in programming circles. Although the official Python style guide prefers spaces, other style guides may specify tabs. In any case, consistency is key.)

There are also several rules for managing indentation when a single line of code is broken across multiple lines. The continuation lines should align wrapped elements (like items in an argument list) either vertically or using a hanging indent. See some examples below:

Good practice

# Vertical alignment
congrats = joining_four_strings_and_repeating_three_times('Happy', 
                                                          'New', 
                                                          'Year',
                                                          '!')
																													
																												
# Hanging indent
congrats = joining_four_strings_and_repeating_three_times(
    'Happy', 'New', 
    'Year','!')

Bad practice

# Bad practice since no arguments are allowed in the first line when using hanging indent.
congrats = joining_four_strings_and_repeating_three_times('Happy', 
    'New','Year','!')
print (congrats)

Maximum line length

In Python code, the length of a line should be limited to at most 79 characters. Docstrings and comments have an even shorter limit and should not exceed 72 characters. These are the requirements of the Python standard library. However, if some teams strongly prefer a longer line length, they might increase the maximum length to 99 characters, while keeping docstrings and comments still within 72 characters.

(Note: Line length does not impact the performance of your code. This is merely for readability and cleanliness. Those particular were also arbitrarily specified by the official style guide for consistency, since many people have different preferences.)

Line breaks

Long lines can be broken over multiple lines by wrapping expressions in parentheses and using Python’s implied line continuation inside parentheses. Backslashes can also be acceptable for breaking up lines, but only in cases when implicit continuation cannot be applied (for example, if you’re writing multiple long with statements).

For formulas, the best practice is to break lines before binary operators, since this usually results in more readable code. However, it is also permissible to break a line after a binary operator if this matches your local convention.

Good practice

# Line breaks before binary operators
GDP = (private_consumption 
       + gross_investment 
       + government_investment 
       + government_spending 
       + (exports - imports))

Bad practice

# Line breaks after binary operators
GDP = (private_consumption + 
       gross_investment + 
       government_investment + 
       government_spending + 
       (exports - imports))

Blank lines

It is recommended to surround top-level function and class definitions with two blank lines and method definitions with one blank line. You can also use extra blank lines to separate groups of related functions or to indicate logical sections within a function.

Imports

Any Python code should start with imports of necessary libraries and classes. It is recommended to place imports of different libraries on separate lines. However, it is okay to import several classes from the same module in one line.

Good practice

# Importing different libraries in different lines
import numpy
import pandas

# Importing different classes from the same module
from sklearn.metrics import confusion_matrix, classification_report

Bad practice

# Importing different libraries in one line
import numpy, pandas

How to Comment Python Code Like a Pro

Comments are at the core of good coding practice. It’s very important to document your Python code extensively and keep all the comments up-to-date when the code changes.

Comments should be complete sentences, preferably written in English.

There are three types of comments:

  • Block comments apply to code that follows them. These comments usually consist of one or more paragraphs. All lines of block comment should start with a # and a single space. It is a good practice to separate paragraphs inside a block comment with a line containing a single #.
  • Inline comments are comments on the same line as a statement. This type of comment should be used sparingly and only for really useful explanations. Otherwise, your code will become messy. These comments are to be separated by at least two spaces from the statement and start with a # followed by a single space.
  • Documentation strings (or docstrings) come at the beginning of modules, functions, classes, and methods. A docstring is surrounded by “““triple double quotes”””. In contrast to usual comments, a docstring serves not as a description but as a command—for example, "Form a complex number" or "Return a single string”.

Python Naming Conventions

Python code accepts different naming styles, but there are some recommended styles that you should follow for certain objects.

Let’s first start with Python naming styles. These include:

  • b (single lowercase letter)
  • B (single uppercase letter)
  • lowercase and lowercase_with_underscores
  • UPPERCASE and UPPERCASE_WITH_UNDERSCORES
  • CapitalizedWords and Capitalized_Words_With_Underscores
  • mixedCase (also known as camel case)

Now it’s time to move on to the guidelines for using these naming styles in specific situations and for particular objects:

  • Use lowercase or lowercase_with_underscores (if necessary for better readability) for function names as well as variable names. A function name should convey what it does.
  • Don’t use a single lowercase letter ‘l’ (el), an uppercase letter ‘I’ (eye), or an uppercase letter ‘O’ as a variable name. In some fonts, these characters are indistinguishable from numbers like ‘1’ and ‘0’.
  • Don’t name your variables like ‘x’ or ‘y’. Instead, use descriptive names (e.g., fertility_rate_1990, gdp_1990).
  • Try to avoid using excessively long names, especially if certain parts of the name don’t improve your understanding of the code. For example, use actor_names instead of list_of_actor_names.
  • Constants should be named following UPPERCASE or UPPERCASE_WITH_UNDERSCORES naming conventions. It should be clear that the variable is constant just from looking at it.

Sometimes, it is just not feasible to follow all the naming conventions because some of your existing code base follows different conventions, or there are some other locally adopted conventions that you adhere to. In any case, remember that consistency within your project is more important than following any particular style guide.

Wrap-up

Professional programmers avoid writing complex code, as more complexity implies more bugs. You want to write code in the simplest way possible to ensure that it can be easily understood by both yourself and another programmer. In fact, Python was created to be clear and understandable—that’s why good Python code that follows some of these conventions reads almost like English!

You’re now familiar with the basic style guidelines for Python code, but there are many more to discuss. Learn additional best practices for writing Python code professionally with our courses: Python Basics (Part 1, Part 2, Part 3) and Introduction to Python for Data Science.

Kateryna Koidan

Kateryna is a data science writer from Kyiv, Ukraine. She worked for BNP Paribas, the leading European banking group, as an internal auditor for more than 6 years. More recently, she decided to pursue only the favorite part of her job—data analysis. Now she is continuing her self-education with deep-learning courses, enjoys coding for data analysis and visualization projects, and writes on the topics of data science and artificial intelligence. Kateryna is also a proud mother of two lovely toddlers, who make her life full of fun.

comments powered by Disqus