16. PEP 8 Compliance

Additional Tips:

  • Avoid using import *: This is discouraged because it can lead to namespace pollution.

  • Use triple quotes for multi-line strings: This is a good practice for strings that span multiple lines.

By adhering to PEP 8, you can write Python code that is clean, readable, and consistent, improving maintainability and collaboration.


1. Import Statements

PEP 8 recommends grouping imports into three categories: standard library imports, third-party imports, and local application imports. They should be separated by a blank line.

Copy

# Standard library imports
import os
import sys

# Third-party imports
import requests

# Local application imports
from my_module import my_function

2. Variable Naming

PEP 8 recommends using lowercase words separated by underscores for variable names, with an exception for class names, which should use the CapitalizedWords convention.

Copy


3. Function Naming

Function names should be written in lowercase, with words separated by underscores.

Copy


4. Indentation

PEP 8 recommends using 4 spaces per indentation level.

Copy


5. Line Length

PEP 8 recommends limiting lines to 79 characters. If a line is longer, break it into multiple lines.

Copy


6. Blank Lines

PEP 8 suggests using two blank lines before class and function definitions and one blank line between methods in a class.

Copy


7. Spaces in Expressions and Statements

PEP 8 advises using spaces around operators and after commas, but not before parentheses or indexing brackets.

Copy


8. Commenting Code

PEP 8 encourages writing comments that explain "why" rather than "what." Comments should be in full sentences and should start with a capital letter.

Copy


9. Docstrings for Functions and Methods

PEP 8 recommends using docstrings to document all public classes and functions. The docstring should summarize the function's behavior and list its arguments and return values.

Copy


10. Consistent Use of self in Class Methods

PEP 8 specifies that the first argument of an instance method in a class should always be self, while the first argument of a class method should always be cls.

Copy


Last updated