extend config init to allow YAML string and key=value pairs
This commit is contained in:
parent
727dd8936d
commit
d5da47bf71
|
@ -38,6 +38,15 @@ class NiceDumper(yaml.SafeDumper):
|
|||
class Config(dict):
|
||||
"""YAML-based configuration."""
|
||||
|
||||
def __init__(self,yml=None,**kwargs):
|
||||
"""Initialize from YAML, dict, or key=value pairs."""
|
||||
if isinstance(yml,str):
|
||||
kwargs.update(yaml.safe_load(yml))
|
||||
elif isinstance(yml,dict):
|
||||
kwargs.update(yml)
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def __repr__(self):
|
||||
"""Show as in file."""
|
||||
output = StringIO()
|
||||
|
|
|
@ -17,18 +17,24 @@ class ConfigMaterial(Config):
|
|||
|
||||
"""
|
||||
|
||||
def __init__(self,d=None):
|
||||
def __init__(self,d=None,**kwargs):
|
||||
"""
|
||||
New material configuration.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
d : dictionary, optional
|
||||
d : dictionary or YAML string, optional
|
||||
Initial content. Defaults to None, in which case empty entries for
|
||||
material, homogenization, and phase are created.
|
||||
any missing material, homogenization, and phase entry are created.
|
||||
kwargs : key=value pairs, optional
|
||||
Initial content specified as pairs of key=value.
|
||||
|
||||
"""
|
||||
super().__init__({'material': [], 'homogenization': {}, 'phase': {}} if d is None else d)
|
||||
if d is None:
|
||||
for section,default in {'material':[],'homogenization':{},'phase':{}}.items():
|
||||
if section not in kwargs: kwargs.update({section:default})
|
||||
|
||||
super().__init__(d,**kwargs)
|
||||
|
||||
|
||||
def save(self,fname='material.yaml',**kwargs):
|
||||
|
|
|
@ -59,3 +59,11 @@ class TestConfig:
|
|||
@pytest.mark.parametrize('data',[Rotation.from_random(),Orientation.from_random(lattice='cI')])
|
||||
def test_rotation_orientation(self,data):
|
||||
assert str(Config(a=data)) == str(Config(a=data.as_quaternion()))
|
||||
|
||||
def test_initialize(self):
|
||||
yml = """
|
||||
a:
|
||||
- 1
|
||||
- 2
|
||||
"""
|
||||
assert Config(yml) == Config('{"a":[1,2]}') == Config(a=[1,2]) == Config(dict(a=[1,2]))
|
||||
|
|
Loading…
Reference in New Issue