How to write comments in YAML

Overview

YAML is a popular data serialization format that is commonly used in many different programming languages. In order to write effective YAML code, it is important to understand how to use comments effectively. This involves understanding the syntax for adding comments as well as knowing when and where to use them.

Syntax

Comments in YAML are denoted by using the hash symbol # at the beginning of the comment line. For example, the following code snippet shows how to add a single-line comment:

# This is a single-line comment

A comment can begin anywhere in the line. See the example below to understand how this can be done:

---
key: "value" # mapping
# A list of two items
list:
- "item 1" # first value
- "item 2" # second value
---

The hash # marks the beginning of a comment and any text until the end of the line is considered part of the comment. Hence, it is completely ignored by YAML parsers.

YAML does not support block or multi-line comments. In order to create a multi-line comment, we need to add # at the beginning of each line.

# This is a multi-line
# comment in YAML. There is
# no alternate way of creating
# block comments.

When and where to use comments

In general, it's a good idea to use comments sparingly and only when absolutely necessary. This is because adding too many comments can actually make the code more difficult to read and understand. In most cases, it's best to add comments where the code is complex or convoluted, or where there is a need to provide additional instructions on how to use certain features.

Additionally, we should avoid using comments to duplicate information that is already provided in the documentation or existing comments.

Conclusion

The use of effective comments in YAML can help make our code more readable and easier to understand for other programmers. To become skilled in YAML, it's important to understand the syntax for adding comments as well as when and where to use them.

By following these basic tips mentioned above, we can write code that is both clean and well-documented.

Unlock your potential: YAML basics series, all in one place!

To continue your exploration of YAML basics, check out our series of Answers below:

Free Resources