-
Notifications
You must be signed in to change notification settings - Fork 2
Coding Style Guide
Nam Mai edited this page Jun 10, 2024
·
1 revision
This document serves as a quick reference for adhering to Python's coding conventions as outlined in PEP 8. Additionally, the tool ruff is recommended for automatic code formatting to ensure consistent style throughout the codebase.
- Indentation
- Whitespace
- Imports
- Comments
- Naming Conventions
- Function and Method Arguments
- Code Organization
- Exceptions
- Whitespace in Expressions and Statements
- Automatic Code Formatting with
ruff
- Use 4 spaces per indentation level.
- Avoid extraneous whitespace.
- Use blank lines to separate functions, classes, and blocks of code inside functions.
- Imports should usually be on separate lines.
- Group imports in the following order:
- Standard library imports.
- Related third-party imports.
- Local application/library specific imports.
- Write comments sparingly and use them to explain complex sections.
- Avoid redundant comments that only repeat the code.
- Follow PEP 8 naming conventions for variables, functions, and classes.
- Put a space after the comma in function and method arguments.
- Organize code logically, with related functions and classes grouped together.
- Use blank lines to separate logical sections within a function.
- Catch specific exceptions instead of using a generic
except
clause. - Use
try
andexcept
blocks only for code that may raise exceptions.
- Avoid extraneous whitespace in expressions and statements.
To ensure consistent code formatting, the tool ruff can be used. ruff
is an opinionated code formatter that automatically formats Python code to comply with PEP 8. Follow the instructions below to use ruff
:
- Install
ruff
using pip:
poetry add ruff
- To run Ruff as a linter, try any of the following:
ruff check . # Lint all files in the current directory (and any subdirectories).
ruff check path/to/code/ # Lint all files in `/path/to/code` (and any subdirectories).
ruff check path/to/code/*.py # Lint all `.py` files in `/path/to/code`.
ruff check path/to/code/to/file.py # Lint `file.py`.
ruff check @arguments.txt # Lint using an input file, treating its contents as newline-delimited command-line arguments.
- Or, to run Ruff as a formatted:
ruff format . # Format all files in the current directory (and any subdirectories).
ruff format path/to/code/ # Format all files in `/path/to/code` (and any subdirectories).
ruff format path/to/code/*.py # Format all `.py` files in `/path/to/code`.
ruff format path/to/code/to/file.py # Format `file.py`.
ruff format @arguments.txt # Format using an input file, treating its contents as newline-delimited command-line arguments.