Custom Code Formatters¶
To create a custom code formatter, create a class that inherits from the CodeFormatter class and implements the format_code method. The format_code method should accept a the unformatted code block as a string, the base indent size, the indent size, and the line width as arguments and should return the formatted code block as a string.
The following example shows a custom code formatter that formats code using textwrap.fill:
custom_formatter.py¶
import textwrap
from g_docformatter.code_formatters import CodeFormatter
class SimpleCodeFormatter(CodeFormatter):
"""Formatter that uses ``textwrap.fill`` to format the code."""
def format_code(
self, code: str, base_indent: int, indent_size: int, width: int
) -> str:
return (
textwrap.fill(
code,
width=width - (base_indent + indent_size * 2),
initial_indent=" " * (base_indent + indent_size * 2),
subsequent_indent=" " * (base_indent + indent_size * 2),
)
+ "\n"
)
Note
To use the custom code formatter, specify the fully qualified class name for the code formatter class in the configuration. See Configuration for more information.