PEP 8, officially titled “PEP 8 — Style Guide for Python Code,” is a document that provides guidelines and best practices for writing Python code. Created by Guido van Rossum and first published in 2001, PEP 8 aims to improve the readability and consistency of Python code by providing a set of conventions for formatting, naming, and structuring code.
Key Components of PEP 8:
- Code Layout:
- Indentation: Use 4 spaces per indentation level. Avoid using tabs.
- Maximum Line Length: Limit all lines to a maximum of 79 characters. For docstrings or comments, the maximum line length is 72 characters.
- Blank Lines: Use blank lines to separate top-level function and class definitions, and to divide the code into logical sections.
-
Imports:
- Import statements should be placed at the top of the file, just after any module comments and docstrings, and before module globals and constants.
- Imports should be grouped in the following order: standard library imports, related third-party imports, and local application/library-specific imports. Each group should be separated by a blank line.
- Avoid wildcard imports (e.g.,
from module import *
).
-
Whitespace in Expressions and Statements:
- Avoid extraneous whitespace in the following situations:
- Immediately inside parentheses, brackets, or braces.
- Immediately before a comma, semicolon, or colon.
- Immediately before the open parenthesis that starts the argument list of a function call.
- Around operators, except for assignment operators.
- Avoid extraneous whitespace in the following situations:
-
Comments:
- Comments should be complete sentences. Use capital letters and periods.
- Place inline comments on the same line as the statement they refer to, separated by at least two spaces.
- Use block comments to explain code that is complex or not immediately clear.
-
Naming Conventions:
- Follow standard naming conventions: use lowercase with words separated by underscores for functions and variable names (e.g.,
my_function
). - Use CamelCase for class names (e.g.,
MyClass
). - Use UPPERCASE with underscores for constants (e.g.,
MY_CONSTANT
).
- Follow standard naming conventions: use lowercase with words separated by underscores for functions and variable names (e.g.,
-
Programming Recommendations:
- Use
is
to compare withNone
, not==
. - Avoid using bare
except
clauses. Specify the exception being caught.
- Use
Importance of PEP 8:
Adhering to PEP 8 is important because it ensures consistency and readability in Python code, making it easier for developers to understand and collaborate on projects. It serves as a universal standard for Python code style, promoting best practices and helping maintain a clean and professional codebase.