Below is a minimal example that demonstrates the issue.
First, imports:
from dataclasses import dataclass, field
from typing import List
import yaml
Next, define a class that derives from yaml.YAMLObject:
@dataclass
class Yaz(yaml.YAMLObject):
name: str
items: List[str] = field(default_factory=lambda: ['a', 'b', 'c'])
yaml_tag: str = u'!Yaz'
Demonstrate usage:
Yaz(name='Yazzzy') # >>> Yaz(name='Yazzzy', items=['a', 'b', 'c'], yaml_tag='!Yaz')
Yaz(name='Yazzzy', items=[]) # >>> Yaz(name='Yazzzy', items=[], yaml_tag='!Yaz')
But sometimes I'd like to instantiate an instance from a YAML file. Mock a YAML file:
yaml_str = """---
!Yaz
name: Yazzzy
"""
Load the YAML file into an instance:
yaml.load(yaml_str, Loader=yaml.Loader) # ERROR!
The last line yields the following error:
AttributeError: 'Yaz' object has no attribute 'items'
Is there some sort of hook I'm missing?
Thanks in advance!
Note: I am using Python 3.8 with pyyaml 6.0.