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.
# Standard library importsimport osimport sys# Third-party importsimport requests# Local application importsfrom 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.
3. Function Naming
Function names should be written in lowercase, with words separated by underscores.
4. Indentation
PEP 8 recommends using 4 spaces per indentation level.
5. Line Length
PEP 8 recommends limiting lines to 79 characters. If a line is longer, break it into multiple lines.
6. Blank Lines
PEP 8 suggests using two blank lines before class and function definitions and one blank line between methods in a class.
7. Spaces in Expressions and Statements
PEP 8 advises using spaces around operators and after commas, but not before parentheses or indexing brackets.
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.
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.
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.
# Correct spacing
a = 10 + 20
b = [1, 2, 3, 4]
c = (x * y for x, y in zip(range(3), range(4)))
# Incorrect spacing
a =10+20
b =[1,2,3,4]
# Correct comment
def add(x, y):
# This function returns the sum of x and y
return x + y
# Incorrect comment
def add(x, y):
# add x and y
return x + y
def add(a, b):
"""
Add two numbers together.
Parameters:
a (int or float): The first number.
b (int or float): The second number.
Returns:
int or float: The sum of the two numbers.
"""
return a + b
class MyClass:
def instance_method(self, param):
print(f"Instance method called with {param}")
@classmethod
def class_method(cls, param):
print(f"Class method called with {param}")