Skip to content

Commit

Permalink
Added convert_to_base_types()
Browse files Browse the repository at this point in the history
  • Loading branch information
stuarteberg committed Jan 6, 2019
1 parent 96d6150 commit 0ab2923
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
2 changes: 1 addition & 1 deletion confiddler/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from jsonschema import ValidationError
from .core import load_config, dump_default_config, validate, emit_defaults, flow_style
from .core import load_config, dump_default_config, validate, emit_defaults, flow_style, convert_to_base_types
from . import json
15 changes: 14 additions & 1 deletion confiddler/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import copy
from os import PathLike
from pathlib import Path
from collections.abc import Mapping
from collections.abc import Mapping, Sequence

from jsonschema import validators
from jsonschema.exceptions import _Error, ValidationError
Expand Down Expand Up @@ -425,6 +425,19 @@ def flow_style(ob):
return l


def convert_to_base_types(o):
"""
Convert the given container into a standard dict or list (recursively).
This is useful if you need to pass your config to a function that is
hard-coded to check for dicts or lists rather than Mapping or Sequence.
"""
if not isinstance(o, dict) and isinstance(o, Mapping):
return { k: convert_to_base_types(v) for k,v in o.items() }
if not isinstance(o, (list, str, bytes)) and isinstance(o, Sequence):
return [convert_to_base_types(i) for i in o]
return o


class _Dict(dict):
"""
This subclass allows us to tag dicts with a new attribute 'from_default'
Expand Down
14 changes: 13 additions & 1 deletion confiddler/tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytest
from ruamel.yaml import YAML

from confiddler import load_config, emit_defaults, validate, dump_default_config, flow_style, ValidationError
from confiddler import load_config, emit_defaults, validate, dump_default_config, flow_style, ValidationError, convert_to_base_types

yaml = YAML()
yaml.default_flow_style = False
Expand Down Expand Up @@ -297,5 +297,17 @@ def test_load_from_path():
assert loaded['mystring'] == "DEFAULT"


def test_convert_to_base_types():
d = yaml.load('{"a": [1,2,3], "b": {"x": 1, "y": 2}}')
assert type(d) != dict
assert type(d['a']) != list
assert type(d['b']) != dict

d2 = convert_to_base_types(d)
assert type(d2) == dict
assert type(d2['a']) == list
assert type(d2['b']) == dict


if __name__ == "__main__":
pytest.main(['-s', '--tb=native', '--pyargs', 'confiddler.tests.test_core'])

0 comments on commit 0ab2923

Please sign in to comment.