Mercurial > hgrepos > Python > libs > ConfigMix
changeset 136:eee1dd1f99bf
Simplify the YAML return type check and map a "None" (empty document) result to an empty mapping
| author | Franz Glasner <hg@dom66.de> |
|---|---|
| date | Thu, 05 Apr 2018 09:39:41 +0200 |
| parents | b7b0cea8ec6e |
| children | e84870359e1a |
| files | configmix/yaml.py |
| diffstat | 1 files changed, 30 insertions(+), 15 deletions(-) [+] |
line wrap: on
line diff
--- a/configmix/yaml.py Thu Apr 05 09:23:44 2018 +0200 +++ b/configmix/yaml.py Thu Apr 05 09:39:41 2018 +0200 @@ -26,6 +26,9 @@ __all__ = ["safe_load", "safe_load_all", "load", "load_all"] +DictImpl = OrderedDict or dict + + class ConfigLoader(yaml.Loader): """A YAML loader, which makes all ``!!str`` strings to Unicode. @@ -156,9 +159,11 @@ """ data = yaml.load(stream, Loader) - if OrderedDict: - if not isinstance(data, OrderedDict): - raise TypeError("YAML root object must be a mapping") + # Map an empty document to an empty dict + if data is None: + return DictImpl() + if not isinstance(data, DictImpl): + raise TypeError("YAML root object must be a mapping") return data @@ -168,38 +173,48 @@ """ data_all = yaml.load_all(stream, Loader) - if OrderedDict: - for data in data_all: - if not isinstance(data, OrderedDict): + rdata = [] + for data in data_all: + if data is None: + rdata.append(DictImpl()) + else: + if not isinstance(data, DictImpl): raise TypeError("YAML root object must be a mapping") - return data_all + rdata.append(data) + return rdata def safe_load(stream): """Parse the given `stream` and return a Python object constructed from for the first document in the stream. - Recognize only standard YAML tags and cannot construct an + Recognizes only standard YAML tags and cannot construct an arbitrary Python object. """ data = yaml.load(stream, Loader=ConfigSafeLoader) - if OrderedDict: - if not isinstance(data, OrderedDict): - raise TypeError("YAML root object must be a mapping") + # Map an empty document to an empty dict + if data is None: + return DictImpl() + if not isinstance(data, DictImpl): + raise TypeError("YAML root object must be a mapping") return data def safe_load_all(stream): """Return the list of all decoded YAML documents in the file `stream`. - Recognize only standard YAML tags and cannot construct an + Recognizes only standard YAML tags and cannot construct an arbitrary Python object. """ data_all = yaml.load_all(stream, Loader=ConfigSafeLoader) - if OrderedDict: - for data in data_all: - if not isinstance(data, OrderedDict): + rdata = [] + for data in data_all: + if data is None: + rdata.append(DictImpl()) + else: + if not isinstance(data, DictImpl): raise TypeError("YAML root object must be a mapping") + rdata.append(data) return data_all
