Yamlfix

1.19.1 · active · verified Sun Apr 12

Yamlfix is a simple, opinionated YAML formatter that automatically corrects formatting issues and preserves comments. It ensures consistent styling, adds document headers, corrects truthy strings, removes unnecessary apostrophes, and handles line endings and list styles. The library is actively maintained, with version 1.19.1 released in December 2025, and has a consistent release cadence with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `yamlfix` both as a command-line tool (simulated) and programmatically using `fix_files` to modify a file in place, and `fix_code` to format a YAML string. It highlights how the tool corrects common formatting inconsistencies like indentation, missing document headers, and list styling.

import os
import stat
from yamlfix import fix_files, fix_code

# --- CLI Usage Example ---
# Create a malformed YAML file
malformed_cli_yaml = """
key: value
  another_key:    nested_value
- item1
-    item2
"""

with open("malformed.yaml", "w") as f:
    f.write(malformed_cli_yaml)

# Run yamlfix via CLI (simulate for quickstart)
# In a real scenario, you would run: !yamlfix malformed.yaml
print("\n--- CLI (Simulated) ---")
print("Original malformed.yaml:")
with open("malformed.yaml", "r") as f:
    print(f.read())

# Simulate fixing by reading, fixing with fix_code, and writing back
fixed_content_cli = fix_code(malformed_cli_yaml)
with open("malformed.yaml", "w") as f:
    f.write(fixed_content_cli)

print("Fixed malformed.yaml:")
with open("malformed.yaml", "r") as f:
    print(f.read())

# --- Programmatic Usage Example (fix_files) ---
# Create another malformed YAML file
malformed_file_yaml = """
list:
- item_a
  - item_b
  # A comment
  -item_c
"""

with open("another_malformed.yml", "w") as f:
    f.write(malformed_file_yaml)

print("\n--- Programmatic (fix_files) ---")
print("Original another_malformed.yml:")
with open("another_malformed.yml", "r") as f:
    print(f.read())

# Fix the file(s) programmatically
fix_files(["another_malformed.yml"])

print("Fixed another_malformed.yml:")
with open("another_malformed.yml", "r") as f:
    print(f.read())

# --- Programmatic Usage Example (fix_code) ---
print("\n--- Programmatic (fix_code) ---")
code_to_fix = """
  key1:  value1
key2: value2
"""
print("Original code string:\n" + code_to_fix)
fixed_code_string = fix_code(code_to_fix)
print("Fixed code string:\n" + fixed_code_string)

# Cleanup generated files
os.remove("malformed.yaml")
os.remove("another_malformed.yml")

view raw JSON →