Code Style Guide¶
Consistent Style
Following a consistent code style ensures our codebase remains readable and maintainable. This guide outlines the style conventions used in TorchEBM.
Python Style Guidelines¶
TorchEBM follows PEP 8 with some project-specific guidelines.
Automatic Formatting¶
We use several tools to automatically format and check our code:
-
Black
Automatic code formatter with a focus on consistency.
-
isort
Sorts imports alphabetically and separates them into sections.
-
Flake8
Linter to catch logical and stylistic issues.
Code Structure¶
Naming Conventions¶
Classes¶
Use CamelCase
for class names:
Constants¶
Use UPPER_CASE
for constants:
Documentation Style¶
TorchEBM uses Google-style docstrings for all code documentation.
Docstring Example
Type Annotations¶
We use Python's type hints to improve code readability and enable static type checking:
CUDA Code Style¶
For CUDA extensions, we follow these conventions:
Imports Organization¶
Organize imports in the following order:
- Standard library imports
- Related third-party imports
- Local application/library specific imports
Comments¶
- Use comments sparingly - prefer self-documenting code with clear variable names
- Add comments for complex algorithms or non-obvious implementations
- Update comments when you change code
Good Comments Example
Pre-commit Hooks¶
TorchEBM uses pre-commit hooks to enforce code style. Make sure to install them as described in the Development Setup guide.
Recommended Editor Settings¶
- Install Black and isort plugins
- Configure Code Style for Python to match PEP 8
- Set Black as the external formatter
- Enable "Reformat code on save"
- Configure isort for import optimization
Style Enforcement¶
Our CI pipeline checks for style compliance. Pull requests failing style checks will be automatically rejected.