From a26e586b144d8029bc7f19917a30fc817ef79d6c Mon Sep 17 00:00:00 2001 From: Philip Eisenlohr Date: Tue, 9 Mar 2021 19:15:15 +0000 Subject: [PATCH] More general 'delete' (accepts iterables) and backports of '|' and '|=' for union/add. '|=' would work for python 3.9 without extra code, but '|' unfortunately casts 'damask.Config' (subclass of 'dict') to a 'dict'. --- python/damask/_config.py | 61 ++++++++++++++++++++++--------------- python/tests/test_Config.py | 11 ++++++- 2 files changed, 47 insertions(+), 25 deletions(-) diff --git a/python/damask/_config.py b/python/damask/_config.py index edf3a5676..85f0c208c 100644 --- a/python/damask/_config.py +++ b/python/damask/_config.py @@ -1,5 +1,6 @@ import copy from io import StringIO +from collections.abc import Iterable import abc import numpy as np @@ -44,6 +45,42 @@ class Config(dict): copy = __copy__ + def __or__(self,other): + """ + Update configuration with contents of other. + + Parameters + ---------- + other : damask.Config or dict + Key-value pairs that update self. + + """ + duplicate = self.copy() + duplicate.update(other) + return duplicate + + + def __ior__(self,other): + """Update configuration with contents of other.""" + return self.__or__(other) + + + def delete(self,keys): + """ + Remove configuration keys. + + Parameters + ---------- + keys : iterable or scalar + Label of the key(s) to remove. + + """ + duplicate = self.copy() + for k in keys if isinstance(keys, Iterable) and not isinstance(keys, str) else [keys]: + del duplicate[k] + return duplicate + + @classmethod def load(cls,fname): """ @@ -99,30 +136,6 @@ class Config(dict): fhandle.write(yaml.dump(self,Dumper=NiceDumper,**kwargs)) - def add(self,d): - """ - Add dictionary. - - d : dict - Dictionary to append. - """ - duplicate = self.copy() - duplicate.update(d) - return duplicate - - - def delete(self,key): - """ - Delete item. - - key : str or scalar - Label of the key to remove. - """ - duplicate = self.copy() - del duplicate[key] - return duplicate - - @property @abc.abstractmethod def is_complete(self): diff --git a/python/tests/test_Config.py b/python/tests/test_Config.py index 0319fb6de..9324c28c5 100644 --- a/python/tests/test_Config.py +++ b/python/tests/test_Config.py @@ -23,8 +23,17 @@ class TestConfig: assert Config.load(f) == config def test_add_remove(self): + dummy = {'hello':'world','foo':'bar'} config = Config() - assert config.add({'hello':'world'}).delete('hello') == config + config |= dummy + assert config == Config() | dummy + config = config.delete(dummy) + assert config == Config() + assert (config | dummy ).delete( 'hello' ) == config | {'foo':'bar'} + assert (config | dummy ).delete([ 'hello', 'foo' ]) == config + assert (config | Config(dummy)).delete({ 'hello':1,'foo':2 }) == config + assert (config | Config(dummy)).delete(Config({'hello':1 })) == config | {'foo':'bar'} + def test_repr(self,tmp_path): config = Config()