PEP 8 is a set of conventions for styling Python code. It gives developers shared expectations for imports, names, and common code structures, making code easier for other people to read and work with. Linters and many IDEs can help enforce these conventions. section 3.1 section 3.1.1
Use PEP 8 to move a data-processing script from a quick prototype toward clearer, more maintainable code. Key practices include placing imports on separate lines, avoiding compound statements, using clear naming conventions, not reusing builtins or keywords as variable names, and minimizing global variables. section 3.1.1 section 3.5
Listing 3.1 Poorly written code example
import pandas, numpy #1
num_states = 50 #2
def PROCESSDATA(file_name, int): #3
global df #4
df = pd.read_csv(file_name) #5
df = df.fillna(df.median()) #6
if int > 0: df = df.sample(int) #7
This customer-churn processing script concentrates several style problems: combined imports, an unclear constant, an uppercase function name, a global dataframe, and a one-line conditional. It provides a practical starting point for applying the conventions. section 3.1.1
Common revisions make intent easier to see:
- Put each package import on its own line rather than combining multiple imports. section 3.1.1
- Write an if statement and its body on separate lines instead of using a compound statement. section 3.1.1
- Distinguish constants and functions through consistent names, such as NUM_STATES and process_data. section 3.1.1
- Rename parameters that shadow builtins or keywords, such as changing int to num_samples. section 3.1.1
- Prefer local variables and returned values over modifying globals inside functions. section 3.1.1
Cleaning a data-processing function
A function can read churn data, fill missing values with medians, sample rows when num_samples is positive, and return the resulting dataframe. Naming the function process_data, using num_samples instead of int, and returning df avoids several style problems at once. section 3.1.1
PEP 8 is part of a broader clean-code workflow. Alongside functions, dictionaries, modular files, and tools such as pylint or autopep8, consistent style supports collaboration, portability, maintenance, and production deployment. section 3.9 section 3.5
