Page tree

To follow the 3rd rule of the Zen of Python (see PEP 20), which says 'Simple is better than complex.', simply follow the de-facto standard code style guide for Python (see PEP 8). In order to make your life as a Python developer even more pleasant, there are couple of great tools available to seamlessly apply the PEP 8 guidelines during the development process (see Tools). Happy coding!

PEP 8 -- Style Guide for Python Code

The de-facto standard code style guide for Python is extensively described here PEP 8. While following a particular code style guide lines is important for every professional developer in software project, also keep the following quote from PEP 8 in mind:

 A Foolish Consistency is the Hobgoblin of Little Minds

One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

In particular: do not break backwards compatibility just to comply with this PEP!

Some other good reasons to ignore a particular guideline:

  1. When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
  2. 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).
  3. Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.
  4. When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.

Tools to ease applying the PEP 8 style guide and more

Following a particular style guide can be cumbersome, especially when it is different to personal preferences. Fortunately, there exist tools to help applying style guides, and in the case of python the following two tools are particularly useful and easy to apply (both are part of the Anaconda Python distribution):

  1. pep8 - Python style guide checker
  2. Pylint - Code analysis for Python

Both tools can be either applied from the command lines or fully integrated into various integrated development environments (IDEs). The highly recommended IDE PyCharm comes with the pep8 style guide checker on-board, and other IDEs provide plugins for pep8 support, e.g., Eclipse with PyDev


 

  • No labels