Search code examples
pythonyaml

python yaml save and load a nested class


I have a nested class:

# hello.py
import pydantic as dan

class Hello:
    @dan.dataclasses.dataclass
    class Data:
        data_a: int

import yaml
data = Hello.Data(1)
filename = "hi.yaml"

with open(filename, "w") as fh:
    yaml.dump(data, fh)

with open(filename, "r") as fh:
    yaml.load(fh, yaml.Loader) # Causes the error

It seems the dumper doesn't recognize that the Data is defined inside Hello and saves the class as python/object:hello.Data. I expected python/object:hello.Hello.Data.

Is there a workaround for this?

I have a nested class because I have multiple classes that requires a dedicated dataclass for each.

I found this library. It will be painful for me to add the decorator for each class. But I will try it for now.


Solution

  • Use 'ruamel.yaml' instead of 'pyyaml'. 'pyyaml' has a few limitations in handling nested objects.

    Pip Install:

    pip install ruamel.yaml
    

    Code

    # hello.py
    import pydantic as dan
    
    class Hello:
        @dan.dataclasses.dataclass
        class Data:
            data_a: int
    
    from ruamel import yaml
    
    data = Hello.Data(1)
    filename = "hi.yaml"
    
    with open(filename, "w") as fh:
        yaml.dump(data, fh)
    
    with open(filename, "r") as fh:
        yaml.load(fh, yaml.Loader)  # Causes the error