Skip to content

Commit

Permalink
Implement conversion of numerically-index objects to arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
lune-sta committed Nov 7, 2018
1 parent 0390324 commit 1fc2eb0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions pyhocon/config_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,19 @@ def get_list(self, key, default=UndefinedKey):
value = self.get(key, default)
if isinstance(value, list):
return value
elif isinstance(value, ConfigTree):
try:
lst = []
sorted_tree = sorted(value.items())
for k, v in sorted_tree:
if re.match('^[1-9][0-9]*$|0', k):
lst.append(v)
else:
raise ValueError
return lst
except ValueError:
raise ConfigException(
u"{key} does not translate to a list".format(key=key))
elif value is None:
return None
else:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_config_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ def test_config_list(self):
config_tree.put("a.b.c", [8, 9], True)
assert config_tree.get("a.b.c") == [6, 7, 8, 9]

def test_numerically_index_objects_to_arrays(self):
config_tree = ConfigTree()
config_tree.put("list.2", "b")
config_tree.put("list.0", "a")
assert config_tree.get_list("list") == ["a", "b"]

config_tree.put("invalid-list.a", "c")
config_tree.put("invalid-list.b", "d")
with pytest.raises(ConfigException):
config_tree.get_list("invalid-list")

def test_config_tree_number(self):
config_tree = ConfigTree()
config_tree.put("a.b.c", 5)
Expand Down

0 comments on commit 1fc2eb0

Please sign in to comment.