Search code examples
pythonyamlcomposition

PyYAML - how to deal with composition


I've been trying to use YAML as I love the readability of it.

However, I'm a bit stumped at the best way to put in components/deal with composition.

Let's say I have this as a class I'm trying to replicate:

basicai = aggressiveAI()

fightercomponent = fighter(strength=10, dexterity=5, death=dramaticdeath())

orc = Object(name='orc', hp=100, fighter=fightercomponent, ai=basicai)

How would be the best way to do something like this in YAML?

Mostly, I'd like to be able to not end up with a long list of specifically named component objects and main objects all spread out.


Solution

  • Assuming that you have proper constructors and representers to create the objects, you can do:

    - !AggresiveAI &basicai 
    - !Fighter &fightercomponent
         strength: 10
         dexterity: 5 
         death: dramaticdeath
    - !Object 
        name: orc
        hp: 100
        fighter: *fightercomponent
        ai: *basicai
    

    The only thing problematic is your function call to dramaticdeath as YAML stores objects and not function calls. So make that a lookup from the string to the function in the __init__ method of class Fighter

    The toplevel doesn't have to be a list, you can e.g. make the toplevel a mapping. Just make sure your anchors are defined before using them in aliases.