🖌️ Code Formatting¶
Generated code is automatically formatted using code formatters. By default, black and isort are used to produce consistent, well-formatted output.
🎯 Default Behavior¶
This runs the following formatters in order:
- isort - Sorts and organizes imports
- black - Formats code style
🛠️ Available Formatters¶
| Formatter | Description |
|---|---|
black |
Code formatting (PEP 8 style) |
isort |
Import sorting |
ruff-check |
Linting with auto-fix |
ruff-format |
Fast code formatting (black alternative) |
⚡ Using ruff instead of black¶
Ruff is a fast Python linter and formatter. To use it:
# Use ruff for both linting and formatting
datamodel-codegen --formatters ruff-check ruff-format --input schema.yaml --output model.py
# Use ruff-format as a black replacement
datamodel-codegen --formatters isort ruff-format --input schema.yaml --output model.py
🚫 Disable formatting¶
datamodel-codegen requires at least one formatter when using the CLI --formatters option.
To disable built-in formatting entirely, configure it via pyproject.toml:
⚙️ Configuration via pyproject.toml¶
Formatters read their configuration from pyproject.toml. The tool searches for pyproject.toml in:
- The output file's directory
- Parent directories (up to the git repository root)
📝 Example Configuration¶
[tool.black]
line-length = 100
skip-string-normalization = true
[tool.isort]
profile = "black"
line_length = 100
[tool.ruff]
line-length = 100
[tool.ruff.format]
quote-style = "single"
💬 String Quotes¶
By default, string quote style is determined by your formatter configuration. To force double quotes regardless of configuration:
This overrides skip_string_normalization in black config.
🎨 Custom Formatters¶
You can create custom formatters for specialized formatting needs. See Custom Formatters for details.
📖 See Also¶
- 🖥️ CLI Reference:
--formatters- Specify code formatters - 💬 CLI Reference:
--use-double-quotes- Force double quotes - 🎨 Custom Formatters - Create your own formatters
- ⚙️ pyproject.toml Configuration - Configure datamodel-codegen options