PEP 8 Style Recommendations: Writing Clean and Readable Python Code
2 min readJul 7, 2023
Here are the key PEP 8 style recommendations for Python code in a point-by-point format:
Use Descriptive Variable And Function Names.
- Choose meaningful names that accurately describe the purpose or content of the variable or function
Limit Line Length.
- Keep lines of code under 79 characters.
- Lines can be extended up to 99 characters if necessary, but shorter lines are generally preferred.
Indentation.
- Use 4 spaces for indentation.
- Avoid using tabs or a different number of spaces for indentation.
Use Clear And Consistent Spacing.
- Place one space on each side of binary operators (e.g.,
+
,-
,*
,/
) for improved readability. - Use a single space after commas in function calls or between function arguments.
- Use a single space after a colon in a dictionary (
{key: value}
) or function definition (def function(arg1: int, arg2: str)
).
Vertical Whitespace.
- Use blank lines to separate logical sections or blocks of code within a function or class.
- This improves readability and makes the code easier to navigate.
Comments.
- Use comments to explain non-obvious sections of code or provide context.
- Keep comments concise, clear, and meaningful.
Naming conventions.
- Use lowercase letters and underscores for variable and function names (
my_variable
,calculate_sum()
). - For constants, use uppercase letters with underscores (
MAX_VALUE
,PI
).
Import Statements.
- Place import statements at the top of the file, each on a separate line.
- Group imports by category (standard library, third-party, local) and separate them with a blank line.
String Quotes.
- Use single quotes (
'
) for short strings ('hello'
,'example'
). - Use double quotes (
"
) for long strings or when single quotes are part of the string itself ("I'm happy"
,"This is a long string"
).
Function and Class Definitions.
- Use a single blank line to separate function and class definitions.
- Include a docstring at the beginning of the definition to describe its purpose and usage.
These Recommendations Are Guidelines for Writing Clean and Readable code, but the most important aspect is to ensure clarity and understanding for yourself and your audience.