A style guide is a set of rules and suggestions which shows how to write programs.
Following a style guide helps to make a code more readable. A style guide is essential to maintain readability and consistency across all python projects, modules, functions, etc. The most popular style guides include:
- PEP8: The style guide from python.
- Google Python Style Guide: The style guide used in Google for python codes.
- NumPy: The style guide for documentation of modules, classes, etc.
- TensorFlow Style Guide: It mostly uses PEP8, except for using 2 spaces.
Many projects have their own style guides. PEP8 suggests to give precedence to project-specific guidelines. Individual coders should use PEP8 as it is the official style guide of python.
“Readability Counts.” — Zen of Python.
Key takeaways for beginners:
- Code blocks should be indented with 4 spaces.
- Top level definitions like class definitions should have 2 lines of space before them. Method definitions should be surrounded with 1 line of space. Extra line of space may be used to separate logical sections and function definitions but must be used sparingly.
- Imports should be written on separate lines and put at the top of the file just after module comments and doc-strings.
- Binary operations should be surrounded by equal spaces. Most of the operators should be surrounded by 1 space except in cases where they are used inside brackets, like slicing.
- Consistency. Style guides cannot put more emphasis on consistency.
Linting is the process of running an automated tool to find bugs and styling errors in a code. It helps to ensure that a python code is following the conventions of styling guides and maintain the readability and consistency that we have been talking about. Some of the most famous linting tools are pylint, pychecker and pep8.
“Code is read much more often than it is written.” — Guido Van Rossum