From 3191866ce09b60f09a0d43360e7e292a15f09296 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 9 Feb 2023 16:38:42 -0800 Subject: [PATCH] add prune_empty and delete() --- masque/library.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/masque/library.py b/masque/library.py index 5e5c80a..95c3132 100644 --- a/masque/library.py +++ b/masque/library.py @@ -799,6 +799,35 @@ class MutableLibrary(Library, MutableMapping[str, 'Pattern'], metaclass=ABCMeta) new._merge(key, self, key) return new + def prune_empty( + self, + repeat: bool = True, + ) -> Set[str]: + # TODO doc prune_empty + trimmed = set() + while empty := set(name for name, pat in lib.items() if pat.is_empty()): + for name in empty: + del lib[name] + for pat in lib.values(): + pat.refs = [ref for ref in pat.refs if ref.target not in empty] + + trimmed |= empty + if not repeat: + break + return trimmed + + def delete( + self: ML, + key: str, + delete_refs: bool = True, + ) -> ML: + # TODO doc delete() + del self[key] + if delete_refs: + for pat in lib.values(): + pat.refs = [ref for ref in pat.refs if ref.target != key] + return self + class WrapROLibrary(Library): mapping: Mapping[str, 'Pattern']