Skip to content

Commit e3dfd09

Browse files
committed
By default to_yaml_dict returns vars(self) and from_yaml_dict returns cls(**dct). Fixes #1
1 parent 69cce01 commit e3dfd09

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

yamlable/base.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,19 +17,21 @@ class AbstractYamlObject(ABC):
1717
Adds convenient methods load(s)_yaml/dump(s)_yaml to any object, to call pyyaml features directly on the object or
1818
on the object class.
1919
20-
Also adds the two abstract methods to_yaml_dict / from_yaml_dict, that are common to YamlObject2 and YamlAble
20+
Also adds the two methods to_yaml_dict / from_yaml_dict, that are common to YamlObject2 and YamlAble.
21+
Default implementation uses vars(self) and cls(**dct), but subclasses can override.
2122
"""
2223

23-
@abstractmethod
2424
def to_yaml_dict(self) -> Dict[str, Any]:
2525
"""
2626
Implementors should transform the object into a dictionary containing all information necessary to decode the
2727
object in the future. That dictionary will be serialized as a YAML mapping.
28+
29+
Default implementation returns vars(self)
2830
:return:
2931
"""
32+
return vars(self)
3033

3134
@classmethod
32-
@abstractmethod
3335
def from_yaml_dict(cls: 'Type[Y]', dct: Dict[Any, Any], yaml_tag: str) -> Y:
3436
"""
3537
Implementors should transform the given dictionary (read from yaml by the pyYaml stack) into an object instance.
@@ -38,11 +40,14 @@ def from_yaml_dict(cls: 'Type[Y]', dct: Dict[Any, Any], yaml_tag: str) -> Y:
3840
Note that for YamlAble and YamlObject2 subclasses, if this method is called the yaml tag will already have
3941
been checked so implementors do not have to validate it.
4042
43+
Default implementation returns cls(**dct)
44+
4145
:param dct:
4246
:param yaml_tag: the yaml schema id that was used for encoding the object (it has already been checked
4347
against is_json_schema_id_supported)
4448
:return:
4549
"""
50+
return cls(**dct)
4651

4752
def dump_yaml(self, file_path_or_stream: Union[str, TextIOBase], **pyyaml_kwargs):
4853
"""

yamlable/tests/test_yamlable.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,19 @@ def is_yaml_tag_supported(cls, yaml_tag: str):
9696
Foo_Err.loads_yaml("!yamlable/yaml.tests.Foo_Err {a: 1, b: hello}\n")
9797

9898
assert "No YamlAble subclass found able to decode object" in str(err_info.value)
99+
100+
101+
def test_yamlable_default_impl():
102+
""" tests that the default implementation works """
103+
104+
@yaml_info(yaml_tag_ns='yaml.tests')
105+
class Foo_Default(YamlAble):
106+
def __init__(self, a, b):
107+
self.a = a
108+
self.b = b
109+
110+
f = Foo_Default(1, 'hello')
111+
s = '!yamlable/yaml.tests.Foo_Default {a: 1, b: hello}\n'
112+
assert dump(f) == s
113+
114+
assert dump(load(dump(load(s)))) == s

0 commit comments

Comments
 (0)