How to Write a Comment in YAML
A comment explains a setting to the next person who reads the file, and programs ignore it. In YAML, a comment starts with #, either on its own line or after a value. The same # catches people out when a value starts with it, such as a colour code. This guide writes both kinds and checks them with Python.
Syntax
# <comment on its own line>
<key>: <value> # <comment after a value>
#: starts a comment. Everything after it, to the end of the line, is ignored.- A space before
#: required when the comment follows a value.
The YAML 1.2.2 specification says: "An explicit comment is marked by a “#” indicator." and "Comments must be separated from other tokens by white space characters."
The Example
comments.yaml holds a bike shop's name and opening hours, with a comment at the top and one after the hours.
Prerequisites
- uv and Python, with PyYAML in a project (
uv add pyyaml), to check the file. This guide uses PyYAML 6.0.4 on Python 3.15.2.
Step 1: Write the File
# Settings for the bike shop
name: Bike shop
open_hours: 8 # from 9 am to 5 pm

Step 2: Check It with PyYAML
Save this checker as show.py. It loads any YAML file you give it and prints the result:
import sys
from pprint import pp
import yaml
with open(sys.argv[1], encoding="utf-8") as file:
pp(yaml.safe_load(file))
uv run python show.py comments.yaml
{'name': 'Bike shop', 'open_hours': 8}

Both comments are gone, and open_hours is still the number 8. The command works unchanged in PowerShell.
A Value That Starts with
A colour code starts with #, and after a space, # begins a comment. This file:
colour: #ff0000
loaded as:
{'colour': None}
The colour became a comment, and the key was left with no value. In quotes, colour: "#ff0000", it loaded as {'colour': '#ff0000'}.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
A value starting with #: colour: #ff0000 | It loads as None, without an error | Quote it: colour: "#ff0000" |
No space before an inline comment: open_hours: 8#note | The # isn't a comment there, so the value became the text '8#note' instead of the number 8 | Put a space before # |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
A setting loads as None | Its value starts with #, so it became a comment | Put the value in quotes |
FAQ
How do I write a comment over several lines?
Start each line with #.
Do comments reach my program?
No. The specification says comments "must not be used to convey content information", and safe_load dropped both of them.
Conclusion
The # lines in comments.yaml vanished on loading, and the settings stayed as they were. A value that begins with # needs quotes, or it becomes a comment too.
Additional Resources
- Comments — the specification's rules.
- PyYAML documentation — the library used to check the files.
