How to Add Comments in a YAML File: Where # Works

Updated

yaml comments

A # starts a YAML comment only when it begins a line or follows whitespace — the YAML 1.2.2 specification requires comments to be separated from other tokens by white space characters. Everywhere else it is an ordinary character in the value:

key: a#b     ->  {'key': 'a#b'}      # NOT a comment
key: a #b    ->  {'key': 'a'}        # a comment
key: "a # b" ->  {'key': 'a # b'}    # NOT a comment
key: http://x.test/p#frag
             ->  {'key': 'http://x.test/p#frag'}

Those are PyYAML’s actual return values. Psych returns the same four. The URL case is the one that bites: a fragment in an unquoted URL survives, but insert one space before the # and you have silently truncated the value with no error.

There is no block-comment syntax, and nothing pretends there is

key: /* not a comment */  ->  {'key': '/* not a comment */'}

To comment out five lines you prefix five lines with #. There is one kind of comment. Two consecutive # lines are two comments that happen to be adjacent, which matters as soon as you try to write a tool that manipulates them.

The trap: comments do not survive a load and dump

This is the practical failure, and no error is raised when it happens. Given this file:

# Top-of-file: owned by the platform team
service:
  name: api        # the public name
  # replicas was 4 until the 2026-03 incident
  replicas: 2

Load it and write it back out with PyYAML (safe_load then safe_dump) or with Ruby’s Psych (safe_load then to_yaml) and both return the same thing:

service:
  name: api
  replicas: 2

The reason the incident note existed is gone, and the diff looks like a harmless reformat. Any script that “just updates one field” in a checked-in YAML file does this. ruamel.yaml keeps them, because its default round-trip loader carries the comments on the parsed objects rather than discarding them at parse time:

from ruamel.yaml import YAML
import sys
y = YAML()               # round-trip mode is the default
y.dump(y.load(open('in.yaml')), sys.stdout)

Byte-for-byte identical to the input, including the column the end-of-line comment sits in. That was checked by comparing the two strings, not by eye.

ruamel.yaml can also add a comment from code: data.yaml_add_eol_comment('This is a MySQL database', 'database'), followed by a dump of the document, produces:

# Example configuration
database: mysql  # This is a MySQL database

Comment placement that is not valid YAML

Take this demonstration of comment placement:

key: value # This comment applies to a single key-value pair
# This comment applies to the following sequence
- list item 1
- list item 2

Both parsers refuse it, and not because of the comments — you cannot follow a mapping with a top-level sequence:

PyYAML: yaml.parser.ParserError: while parsing a block mapping ...
        expected <block end>, but found '-'
Psych:  Psych::SyntaxError: did not find expected key
        while parsing a block mapping at line 1 column 1

Comments cannot go just anywhere — key:#value parses to the plain string 'key:#value', not a mapping, because : needs the following space to act as a key separator. And a # inside a quoted string is not a problem at all; it is simply not a comment, which is the second line of the first example above.

Two places a leading # is content, not a comment

Inside a block scalar, everything indented under it is data:

key: |
  line one
  # not a comment
  line two

->  {'key': 'line one\n# not a comment\nline two\n'}

Both parsers agree. If you are storing a shell script or a config fragment in a | block, its # lines are safe. For everything else about | and >, see YAML multiline strings.

Do not put a tab before a comment

This is the one case where the two parsers disagree, which makes it worth avoiding rather than reasoning about:

key: a<tab>#b

PyYAML: yaml.scanner.ScannerError: while scanning for the next token
        found character '\t' that cannot start any token
Psych:  {"key"=>"a"}   (treats it as a comment)

Use a space. The same file is a parse error in one implementation and a valid document in the other, and nothing tells you which one your CI is running. If the parsers on your machine disagree with any of this, how-to-add-yaml-comments.sh names the case that differs: it re-parses the documents above with PyYAML, repeats the key cases in Psych and the byte-for-byte round trip in ruamel.yaml, and skips those two parts when Ruby or ruamel.yaml is not installed.

What was not tested

Everything above is repr() or inspect output from PyYAML 6.0.2 (CPython 3.9.6), Ruby 2.6.10 / Psych 3.1.0 / libyaml 0.2.1, and ruamel.yaml 0.19.1, on macOS 26.6 (arm64). PyYAML and libyaml share no code, so the cases where they agree are meaningful and the tab case is the only one where they did not. Not tested here: Go’s gopkg.in/yaml.v3, js-yaml, snakeyaml, or any YAML 1.1 parser — comment syntax is unchanged between 1.1 and 1.2, but this page does not verify that on a 1.1 implementation.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.