How to Handle Comments in YAML Files using Python

Handling comments in YAML files ensures that your configurations remain understandable and maintainable.

In this tutorial, you’ll learn how to manage comments in YAML files using Python.

 

 

Read YAML Files While keeping Comments

To preserve comments when reading YAML files, use the ruamel.yaml library.

from ruamel.yaml import YAML
yaml = YAML()
with open('config.yaml') as f:
    data = yaml.load(f)
print(data)

Output:

{'database': {'host': 'localhost', 'port': 3306}, 'users': ['Ahmed', 'Fatima', 'Omar']}

This code reads the YAML file config.yaml while retaining all comments.

 

Insert Comments into Specific Locations

You can insert comments before a particular mapping or sequence item using ruamel.yaml.

from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap
yaml = YAML()
with open('config.yaml') as f:
    data = yaml.load(f)
data.yaml_set_comment_before_after_key('users', before='List of authorized users')
with open('config.yaml', 'w') as f:
    yaml.dump(data, f)

Output:

database:
  host: localhost
  port: 3306
  password: securepassword
# List of authorized users
users:
  - Ahmed
  - Fatima
  - Omar

This code adds a specific comment before the users key.

 

Add Comments to Anchors and Aliases

You can add comments to anchors and aliases using yaml_set_comment_before_after_key:

from ruamel.yaml import YAML
from ruamel.yaml.comments import CommentedMap
new_data = CommentedMap()
yaml = YAML()
with open('config.yaml') as f:
    data = yaml.load(f)
new_data['database'] = data['database']
new_data.yaml_set_comment_before_after_key('database', before='This is the default database configuration')
with open('data.yaml', 'w') as f:
    yaml.dump(data, f)

Output:

database: &default
  host: localhost
  port: 3306
  password: securepassword
# Default database settings
default: *default
users:
  - Ahmed
  - Fatima
  - Omar

Here, a comment is added before the default anchor.

 

Modify Existing Comments

You can modify existing comments to update or clarify information.

from ruamel.yaml import YAML
yaml = YAML()
with open('config.yaml') as f:
    data = yaml.load(f)
data.yaml_add_eol_comment('Updated list of users', key='users', column=0)
with open('config.yaml', 'w') as f:
    yaml.dump(data, f)

Output:

database:
  host: localhost
  port: 3306
  password: securepassword
users: # Updated list of users
  - Ahmed
  - Fatima
  - Omar

This script updates the end-of-line comment for the users key.

 

Handle Block Comments in Sequences

You can insert a comment before the first item in a list using yaml_set_comment_before_after_key:

from ruamel.yaml import YAML
yaml = YAML()
with open('data.yaml') as f:
    data = yaml.load(f)
data['users'].yaml_set_comment_before_after_key(0, before='Primary user')
with open('data.yaml', 'w') as f:
    yaml.dump(data, f)

Output:

database:
  host: localhost
  port: 3306
  password: securepassword
users:
  # Primary user
  - Ahmed
  - Fatima
  - Omar

A comment is inserted before the first item in the users list.

 

Add Multi-line Comments

Adding multi-line comments enhances detailed explanations within the YAML file.

from ruamel.yaml import YAML
yaml = YAML()
with open('config.yaml') as f:
    data = yaml.load(f)
multi_line_comment = """\
This section defines the database configuration.
Ensure that the host and port are correctly set.
"""
data.yaml_set_comment_before_after_key('database', before=multi_line_comment)
with open('config.yaml', 'w') as f:
    yaml.dump(data, f)

Output:

# This section defines the database configuration.
# Ensure that the host and port are correctly set.
database:
  host: localhost
  port: 3306
  password: securepassword
users:
  # Primary user
- Ahmed
- Fatima
- Omar

A detailed multi-line comment is added before the database section.

Leave a Reply

Your email address will not be published. Required fields are marked *