Anchors and Aliases are like magic spells that turn a humble apprentice into a YAML wizard. They give your data the power to define and re-use common values.
Anchors and Aliases
You can think of an anchor like a bookmark. It marks a place in your YAML document so you can easily find it later. And aliases? They're the magical map that leads you back to your bookmarks.
In the kingdom of YAML, anchors are represented by the & character, and aliases by the * character.
Enough with the chit-chat, let's meet them in action:
default_settings: &default_settings # Anchoring the block of data
player:
lives: 3
power: 100
player1:
<<: *default_settings # Using the anchored data
player2:
<<: *default_settings # Using the anchored data again
lives: 5 # Overriding a part of the anchored data
In the above example, default_settings
is an anchor that has a dictionary as its value. player1
and player2
are using this anchored dictionary using aliases. Notice how we can also override a part of the anchored data in player2
. Player 2 must have found a secret bonus life!
Using &
and *
for reusability
&
and *
help us write DRY (Don't Repeat Yourself) code. Do you like writing the same thing over and over again? Me neither. With &
and *
, we don't have to.
Let's imagine we have a troop of knights, and they all have the same base attributes. We would use an anchor (&
) to define these common attributes once. Then we use an alias (*
) to apply these attributes to each knight. If a knight has a unique attribute, we can easily add that on without messing with the common attributes.
default_knight: &default_knight
strength: 10
defense: 5
agility: 7
knight1:
<<: *default_knight
knight2:
<<: *default_knight
agility: 10 # this knight is extra agile!
knight3:
<<: *default_knight
strength: 15 # this knight has been hitting the gym!
In this example, knight1
is a carbon copy of default_knight
. knight2
and knight3
, however, have been hitting the gym and agility course respectively, so they've got some pumped-up stats!
And there you have it!
In YAML,
&
and*
are more than just characters. They're the mystical symbols that bring forth the power of reusability. They're the magic in your YAML wizard's spellbook.