Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a yaml file with aliases through PyYAML

I need to create a yaml file with the following format:

imager: &imager
  type: "detector"
  half_angle: 75 degrees
  max_distance: 23000 meters
ownship: &ownship
  origin: [11,11,5]
  type: "uav"

vehicles:
  - <<: *ownship
  name: "uav1"
  origin: [35.69257148103399 degrees, -117.689417544709 degrees, 5500]
  sensors:
    - <<: *imager
      name: "imager1"

I have all the specific data stored in Python classes, so I figured I'd use PyYAML to make things easy. However, when I went to read the documentation, I saw no mention of how to handle aliases with PyYAML. Does this functionality exist, or should I just go ahead and make my own yaml writer?

like image 211
EagerIntern Avatar asked Feb 09 '23 19:02

EagerIntern


1 Answers

It looks as if PyYAML does the right thing if your python data structure contains multiple references to the same object. Consider, for example, this:

>>> a = {'name': 'bob', 'office': '100'}
>>> b = {'president': a, 'vice-president': a}
>>> b
{'president': {'name': 'bob', 'office': '100'}, 'vice-president': {'name': 'bob', 'office': '100'}}
>>> import yaml
>>> print yaml.dump(b)
president: &id001 {name: bob, office: '100'}
vice-president: *id001

PyYAML has recognized that the values for both the 'president' and 'vice-president' keys are references to the same object, and has created an alias and used it appropriately.

like image 53
larsks Avatar answered Feb 12 '23 08:02

larsks