YAML Best Practices
YAML has a Core Development Team
of
five people that I am a member of.
In May 2024, 4 of us met in Berlin. One of the things we did was to write a list of best practices for YAML. We came up with a list of 40 or so things that we all agreed on.
Today I'll share some of those with you.
Don't quote strings that don't need to be quoted🔗
One of the main points of YAML was to create a format that consisted of more data and less syntax.
People tend to quote strings that contain anything they are not sure about, instead of learning the rules for when to quote and when to not quote.
Scalar values without quotes are called "plain scalars".
The basic rules for plain scalars are pretty simple:
- They can't start with these characters:
!
,@
,#
,%
,&
,*
,|
,>
,,
,{
,}
,[
,]
,>
,?
,'
,"
, a backtick or whitespace - They can't contain
:
or#
combinations - They can't end with whitespace
That's pretty much it.
If you're not sure, don't quote it!
Prefer single quotes over double quotes🔗
For some reason, people tend to use double quotes for strings much more than single quotes.
Single and double quoted strings have different semantics in YAML.
Double quoted strings provide a way to escape characters.
Single quoted strings only provide a way to escape a single quote (use 2 single quotes to escape a single quote).
Only use double quotes if you need to escape something.
Note: In YS (code mode) double quoted strings also provide a way to interpolate variables.
Use JSON's true
, false
and null
🔗
The YAML 1.2 core schema lets you use TRUE
and True
variants of true
.
Same for false
and null
.
Stick to the JSON standard of true
, false
and null
.
For null values in mappings you can also use the empty string (nothing) to
represent null
.
a null value: null
also null:
don't use: NULL
That can be useful in YS too. Print a blank line with:
say: 'one'
say: # blank line
say: 'two'
Non-empty YAML files should end with a newline🔗
There are some edge cases where different YAML parsers will disagree on the meaning of a YAML file when it doesn't end with a newline.
It's best to end your YAML files with a newline. Most editors can be configured to add a newline at the end of the file.
Do it.
Don't block sequences in mappings🔗
This one is a bit controversial.
When you have a sequence in a mapping, the -
essentially counts as
indentation.
a mapping:
- a sequence
Many people will indent it like this:
a mapping:
- a sequence
You won't be arrested by the YAML police for doing this, but the core team prefers the former style.
Use .yaml
file extensions🔗
We always wished that people would use the .yaml
file extension for YAML
files.
At some point people started using .yml
extensions and we didn't yell about
it.
We know that ship has sailed, but we still prefer .yaml
over .yml
if you
are starting something new and have the choice.
50 Posts!🔗
If you haven't noticed the Summer of YS blog series is over half way done!
Today is the 50th post in the series!!!