From 209829ffe34cb376f715bf4ef65e7307ea911931 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maximilian=20Ke=C3=9Fler?= Date: Wed, 9 Feb 2022 12:38:40 +0100 Subject: [PATCH] better cleaning functions / add documentation --- PyTeX/format/config.py | 44 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/PyTeX/format/config.py b/PyTeX/format/config.py index af09e86..5965dd5 100644 --- a/PyTeX/format/config.py +++ b/PyTeX/format/config.py @@ -1,26 +1,58 @@ from __future__ import annotations import json from pathlib import Path -from typing import Dict, Optional, Union +from typing import Dict, Optional, Union, List import yaml +def clean_list(list_: List) -> Optional[List]: + """ + Recursively removes all entries from list that are None, + empty dictionaries or empty lists. + Dicts ore lists that are None after cleaning will also be removed + + Typically applied before dumping data to JSON where None values are default + and will be restored on read-in 'automatically' + + :return: + :param list_: Any list + :return: + """ + ret = [] + for elem in list_: + if type(elem) == list: + ret.append(clean_list(elem)) + elif type(elem) == dict: + ret.append(clean_dict(elem)) + elif elem is not None: + ret.append(elem) + return ret if ret != [] else None def clean_dict(dictionary: Dict) -> Optional[Dict]: + """ + Recursively removes all entries from dictionary that are None, + empty dictionaries or empty lists. + Keys whose value is a dict / list that only contains non-valued keys will + then also be removed. + + Typically applied before dumping data to JSON where None values are default + and will be restored on read-in 'automatically' + + :param dictionary: Any dictionary + :return: + """ aux: Dict = { k: clean_dict(v) for k, v in dictionary.items() if type(v) == dict } | { - k: [ - clean_dict(elem) if type(elem) == dict else elem - for elem in elems - ] for k, elems in dictionary.items() if type(elems) == list + k: clean_list(v) + for k, v in dictionary.items() if type(v) == list } | { k: v for k, v in dictionary.items() if type(v) != dict and type(v) != list } aux2: Dict = { k: v for k, v in aux.items() if v is not None } - return aux2 if aux2 != {} else None + return aux2 if aux2 != {} and aux2 != [] else None class Config: