5

It is possible, to do several items in YAML file with identical attributes, but with out need to actually duplicate them?
For example, I have:

item1:  
    it_one:  
        some: {...}  
    it_two:
        somemore: {...}
item2:
    the_same_as_in_item1

How can I specify, that item1 and item2 are have the same attributes? At the end I want to:

item1[it_one][some]  
item2[it_one][some]

Give me identical result.

Anthon
  • 69,918
  • 32
  • 186
  • 246
Andreios
  • 53
  • 1
  • 5

1 Answers1

4

The mechanism in YAML that could help you out is using anchors and aliases. With those you have to watch out though, because when you alias a YAML mapping (loaded as a Python dict ), that you will get the same instance of that dict attached to item1 and item2.

If that is not what you want there is a specific interpretation of an alias in the form of a merge key. To use that specify a key <<:

item1: &repl  
    it_one:  
        some: {...}  
    it_two:
        somemore: {...}
item2:
    <<: *repl

this will give you, at least directly under item2 a new dict with the same keys/values as for item1 (i.e. keys it_one, it_two). However again the values for those keys (some: {}) will be the same object, due to the way this is loaded and handled internally.

If that kind of object reuse is problematic, you better stick with a non-merge use of the alias:

item1: &repl  
    it_one:  
        some: {...}  
    it_two:
        somemore: {...}
item2: *repl

and walk over the tree recursively duplicating the key-values in new dicts (and lists).

Please note that if you use the round_trip_loader in ruamel.yaml, you will even share the everything, even when using merge keys. Without that round-tripping would not be possible, so use the safe_loader instead.

Anthon
  • 69,918
  • 32
  • 186
  • 246