This style guide provides guidelines for writing Python code that is readable, maintainable, and consistent.
- Introduction
- Naming Conventions
- Code Formatting
- Comments
- Function and Method Definitions
- Imports
- Exceptions
- Whitespace
- Miscellaneous
- Use
lowercase_with_underscores
for variable and function names. - Use
CAPITALIZED_WITH_UNDERSCORES
for constants. - Use
CamelCase
for class names. - Avoid single-character names, unless they have a well-defined meaning.
- Avoid using reserved keywords as names.
- Use 4 spaces for indentation (avoid tabs).
- Limit lines to a maximum of 79 characters.
- Use a single space around operators and after commas.
- Use blank lines to separate logical sections of code.
- Use comments to explain non-obvious code behavior.
- Write self-explanatory code that reduces the need for comments.
- Use complete sentences and proper grammar in comments.
- Use descriptive names for functions and methods.
- Add a docstring to describe the purpose, inputs, and outputs of the function.
- Limit the number of arguments to keep functions concise.
- Import modules on separate lines, grouped in the following order:
- Standard library imports.
- Third-party library imports.
- Local application imports.
- Avoid using wildcard imports (
from module import *
).
- Catch specific exceptions instead of using a bare
except
clause. - Avoid catching and swallowing exceptions silently.
- Use a single blank line to separate logical sections of code.
- Use blank lines sparingly within functions to improve readability.
- Avoid excessive whitespace at the end of lines or empty lines at the end of files.
- Be consistent with the style guide within a project.
- Write code that is easy to understand and maintain.
- Refactor code to improve readability and eliminate code duplication.
This style guide is inspired by the PEP 8 style guide with a few additional recommendations.