Python Curriculum
Pep8 Style Guide
When working in engineering teams, code readability is critical. Code is read far more often than it is written. If every developer uses their own styling conventions—such as mixing tabs and spaces, using inconsistent variable naming styles, or writing long lines—the codebase becomes difficult to maintain.
PEP 8 is the official style guide for Python code. It provides guidelines for writing clean, consistent, and readable Python code.
In this guide, we will cover the core formatting rules defined in PEP 8, examine imports grouping conventions, analyze naming standards, and compare non-compliant code with PEP 8 compliant examples.
Core Formatting Guidelines
1. Indentation
- Spaces vs. Tabs: Always use 4 spaces per indentation level. Never use tabs.
- Mixing tabs and spaces in Python 3 will raise a
TabErrorat runtime.
2. Maximum Line Length
- Limit all lines to a maximum of 79 characters.
- For docstrings or comments, limit the line length to 72 characters.
- Long lines can be wrapped using Python's implicit line joining inside parentheses, brackets, and braces.
3. Blank Lines
- Surround top-level function and class definitions with two blank lines.
- Surround method definitions inside a class with a single blank line.
4. Imports Formatting
Imports should always be written at the top of the file, right after any module comments and docstrings, and before module globals. Group imports in this order, with a blank line separating each group:
- Standard library imports.
- Related third-party imports.
- Local application/library specific imports.
Naming Conventions
Naming conventions vary depending on the code element:
Non-Compliant vs. PEP 8 Compliant Code
Let's look at a badly styled Python script, followed by its PEP 8 compliant equivalent:
Non-Compliant Implementation:
PEP 8 Compliant Implementation:
Summary
Adhering to the PEP 8 style guide ensures that your Python code is consistent and readable. By using standard indentation, limiting line lengths, grouping imports, and following naming conventions, you can write maintainable code. In the next section, we will cover the Black formatter.