Merge branch 'flexible-yaml-dump' into development

This commit is contained in:
Sharan Roongta 2020-10-28 16:19:17 +01:00
commit 21f095c9d8
2 changed files with 23 additions and 1 deletions

View File

@ -1,6 +1,7 @@
from io import StringIO from io import StringIO
import abc import abc
import numpy as np
import yaml import yaml
class NiceDumper(yaml.SafeDumper): class NiceDumper(yaml.SafeDumper):
@ -15,6 +16,11 @@ class NiceDumper(yaml.SafeDumper):
def increase_indent(self, flow=False, indentless=False): def increase_indent(self, flow=False, indentless=False):
return super().increase_indent(flow, False) return super().increase_indent(flow, False)
def represent_data(self, data):
"""Cast Config objects and its subclasses to dict."""
return self.represent_data(dict(data)) if isinstance(data, dict) and type(data) != dict else \
super().represent_data(data)
class Config(dict): class Config(dict):
"""YAML-based configuration.""" """YAML-based configuration."""
@ -64,7 +70,20 @@ class Config(dict):
kwargs['width'] = 256 kwargs['width'] = 256
if 'default_flow_style' not in kwargs: if 'default_flow_style' not in kwargs:
kwargs['default_flow_style'] = None kwargs['default_flow_style'] = None
fhandle.write(yaml.dump(dict(self),Dumper=NiceDumper,**kwargs)) if 'sort_keys' not in kwargs:
kwargs['sort_keys'] = False
def array_representer(dumper, data):
"""Convert numpy array to list of native types."""
return dumper.represent_list([d.item() for d in data])
NiceDumper.add_representer(np.ndarray, array_representer)
try:
fhandle.write(yaml.dump(self,Dumper=NiceDumper,**kwargs))
except TypeError: # compatibility with old pyyaml
del kwargs['sort_keys']
fhandle.write(yaml.dump(self,Dumper=NiceDumper,**kwargs))
@property @property

View File

@ -1,4 +1,5 @@
import pytest import pytest
import numpy as np
from damask import Config from damask import Config
@ -29,6 +30,8 @@ class TestConfig:
f.write(config.__repr__()) f.write(config.__repr__())
assert Config.load(tmp_path/'config.yaml') == config assert Config.load(tmp_path/'config.yaml') == config
def test_numpy(self,tmp_path):
assert Config({'A':np.ones(3,'i')}).__repr__() == Config({'A':[1,1,1]}).__repr__()
def test_abstract_is_valid(self): def test_abstract_is_valid(self):
assert Config().is_valid is None assert Config().is_valid is None