Languages Python Best Practices for 2021

Python Best Practices for 2021

Whether you are new to programming in Python or have spent a lifetime developing software in the “top 3” language, it is never too late to start implementing the ‘best practices’ for your Python code. We take a look at the top suggestions for creating readable, understandable, and error-free code for 2021. These practices include proper naming conventions, documentation standards, and following style guidelines – to name but a few.

The Zen of Python

One way to understand the best practices for Python coding is to read the poem written by Python guru Tim Peters. If you do not know Tim Peters, he is a major contributor to Python and served on the Python Software Foundation’s board of directors for 13 years. Writing Python code in poem structure or form is a past-time for some of the more eclectic Python developers, so it sort of makes sense that Tim Peters would create his own poem to help express the core values programmers should follow while developing applications in Python.

There are two ways to view The Zen of Python (the poem Tim Peters wrote). The first is to import the module known as this in Python’s built-in code editor, IDLE. To do so, simply write the following code at the command prompt:

# How to import the module this, which allows you to read "The Zen of Python"
import this

Importing this in IDLE will result in the following output, which is the content of Mr. Peter’s poem:

The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let's do more of those!

If you are new to Pythonic programming – or programming in general – then the above poem may not make a ton of sense to you yet. Even seasoned developers may scratch their heads a little when reading it. However, once you better understand Python’s best practices, it is a good poem to revisit, especially if you need a quick and simple reminder of some of the most important coding standards you should be following.

The other way to view this Zen of Python poem is to revisit this article! I know, shameful self-plug…

Best Practices for Python Code

Below you can find some of the best practices for writing Python code. You can also take a look at Python’s PEP 8, the Style Guide for Python Code for additional suggestions.

Document and Comment Your Code Consistently

Commenting and documenting code are phrases that are often used interchangeably, even though they are technically two different things. The confusion probably stems from the similarities between the two. Commenting and documenting are both meant to explain code and portions of software. The difference lies in the intended audience: comments are meant for the coder and any developers that might be looking at the code; documentation is intended for the users of the code or end product. The caveat to that, of course, is that documentation can also benefit developers and the development team.

Code commenting best practices include:

  • Keep comments short and concise when possible. Try not to use long comments.
  • Keep comments near the code they are describing.
  • Keep comments simple. Avoid formatting or use of special characters or ASCII symbols that could distract the reader.
  • Don’t use smelly comments or comments that try to explain bad code.
  • Keep away from W.E.T. comments (Write everything twice or waste everyone’s time), in which you comment on code using the same exact text you used to create the code or where the code is self-explanatory.

You can check out our article How to Comment in Python for more best practices on commenting.

When creating documentation, the following are some best practices for documenting code in Python:

  • Use documenting tools, such as Docstrings and reStructuredText.
  • Use sentence case for section titles, unless rules require differently, such as the use of special names.
  • Write documentation inside the code – which Docstrings allows developers to do.
  • Use an affirmative tone that clearly states what the code does and how to use it.
  • Keep documentation simple. If something does not need to be explained, don’t explain it. Don’t overcomplicate simple concepts.

The Dev Guide has a great section on documentation.

Fix Code Issues Immediately

Sometimes when we are in the heat of the moment or have a new idea or feature we want to add to our applications, a developer can put off fixing broken or troublesome code in favor of writing the newer (perhaps more exciting) code. This is understandable to a degree, but it is definitely a no-no. For starters, once you let this happen once, you can soon find yourself doing it frequently. Soon enough, you have a long list of code issues that need to be fixed that can further impact future code; once fixed, this “fixed” code can then impact those new features you added.

In addition, sometimes broken code can be forgotten if not properly tracked. It is all too easy to let tasks and error tracking fall by the wayside and get lost in the cracks. Not fixing broken code in favoring or adding new code can also negatively impact timelines and deadlines. As errors stack up, it becomes more difficult to accurately gauge how long those problems will take to resolve, leading to unstable development life cycles.

Write Readable Code/Keep Readability in Mind

There is a quote that is often misattributed and misspoken that states: “Code is read much more often than it is written.” It comes from an article by Raymond Chen (from his Microsoft blog The Old New Thing), but it could also come from Robert C. Martin’s book, Clean Code: A Handbook of Agile Software Craftsmanship, who also used a similar quote. Wherever the quote comes from, its intent remains the same: your code gets read a lot, so make sure people can actually read it.

Writing readable code means that you stick to naming conventions for identifiers, classes and objects, file names, data types, functions, and methods. For instance, classes should always be named using the CapWords convention. Examples of this include: NewClass or CarClass. Another example is Exception Names, which also use the CapWord case, but should also end with the suffix Error. For instance, NumberRepetitionError.

It also refers to the use of indentation and the use of tabs versus spaces. Python indentation best practices insist on four spaces per indentation level. in addition, in general, spaces are the preferred method to indent code. Never mix tabs with spaces – pick a side. And have that side be spaces.

Another thing that helps with readability is keeping your line length to a maximum of 79 characters.

For more, always refer to Python’s P.E.P. 8, which lists a plethora of suggested style guidelines for Python developers.

One Statement, One Line

One of the interesting things about the Python language is that you can write multiple statements in one line. However, this violates Python best practices. It makes code very difficult to read, comment in, and understand. It also causes the code to be more difficult to troubleshoot and find errors in. For example, you could write the following code:

age = 42; intelligence = 12; print("Hello, how are you?"); print("Terrible, yourself?")
if age == intelligence: print("You age equals your IQ! Interesting...");

If you run that code in a Python IDE or code editor, it will run without errors. It is perfectly valid code. However, it is very jumbled and difficult to read. Compare it to this version of the same code:

age = 42;
intelligence = 12;
print("Hello, how are you?");
print("Terrible, yourself?")

if age == intelligence: print(“You age equals your IQ! Interesting…”);

Much better.

Create A Proper Repository Structure

When creating software, most developers will want to setup a code repository. They may also want to implement version control and version tracking of some kind. Python repositories should be structured in a specific manner and should include the following elements at the very least:

  • License: This file goes in the root.
  • README: Whatever type of README file or files you decide to use, you will want to include them in the root. This type of file is used to document your software and provide any important information, such as installation instructions, usage, and so forth.
  • Module Code: Found in either root or /module. If you are creating a project with just one file, the code can go in root. If you use multiple files or modules, create a sub-directory within root to keep the files.
  • Another file that belongs in root, is a basic file that lets Distutils build and distribute modules for the project.
  • Docs: Always create a section for documentation. This is typically something like /docs.
  • Tests: Creating a test area is also advisable. Something like /tests works nicely.
  • requirements.txt: Residing in root, this is an optional file, but usually a handy one to have in place. You can use it to inform others know of any pre-requisites or dependencies required by the project.

Test Code Frequently

This should be a no-brainer, but testing your code often is one of the best practices you can incorporate into your coding. Testing your program frequently helps you find errors in code easier and ensures you are not building on erroneous code, which can lead to more issues further down the line. Similar to the concept of fixing errors as they pop up, this idea takes that one step further. After all, if you do not know a problem exists, how can you ever take care of it?

There are plenty of code debugging tools for Python and software testing tools and utilities in general. Other software development tools, like code refactoring software, can help you streamline your code and remove any redundant or poorly coded blocks.

Final Thoughts on Coding Best Practices

A final note on best practices in Python. While you might be tempted to apply the best practices of other programming languages to your Python code, resist that temptation. Some of them may, indeed, make sense for Python, while others could lead you down a bad path and ultimately disrupt your code. After all, every programming language and its core concepts are different, so it makes sense that not every best coding practice works across the board.

Stick to Python best practices, and you will save yourself – and others – a lot of future problems.

Latest Posts

Related Stories