Skip to content

Commit 95a0ca1

Browse files
committed
Fixed flatten not working when separator is equal to keypath_separator. #88
1 parent 7dfccff commit 95a0ca1

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

benedict/dicts/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,11 @@ def flatten(self, separator="_"):
130130
Return a new flattened dict using the given separator
131131
to join nested dict keys to flatten keypaths.
132132
"""
133+
if separator == self._keypath_separator:
134+
raise ValueError(
135+
f"Invalid flatten separator: '{separator}', "
136+
"flatten separator must be different from keypath separator."
137+
)
133138
return _flatten(self, separator)
134139

135140
def get(self, key, default=None):

tests/github/test_issue_0088.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from benedict import benedict
4+
5+
import unittest
6+
7+
8+
class github_issue_0088_test_case(unittest.TestCase):
9+
"""
10+
This class describes a github issue 0088 test case.
11+
https://github.com/fabiocaccamo/python-benedict/issues/88
12+
13+
To run this specific test:
14+
- Run python -m unittest tests.github.test_issue_0088
15+
"""
16+
17+
def test_flatten_without_keypath_separator(self):
18+
d = benedict({"a": {"b": {"c": 1}}}, keypath_separator=None)
19+
f = d.flatten(".")
20+
self.assertEqual(f, {"a.b.c": 1})
21+
22+
def test_flatten_with_separator_equal_to_keypath_separator(self):
23+
d = benedict({"a": {"b": {"c": 1}}}, keypath_separator=".")
24+
with self.assertRaises(ValueError):
25+
f = d.flatten(".")
26+
d = benedict({"a": {"b": {"c": 1}}}, keypath_separator="_")
27+
with self.assertRaises(ValueError):
28+
f = d.flatten("_")
29+
30+
def test_flatten_with_separator_different_from_keypath_separator(self):
31+
d = benedict({"a": {"b": {"c": 1}}}, keypath_separator="_")
32+
f = d.flatten(".")
33+
self.assertEqual(f, {"a.b.c": 1})
34+
d = benedict({"a": {"b": {"c": 1}}}, keypath_separator=".")
35+
f = d.flatten("_")
36+
self.assertEqual(f, {"a_b_c": 1})

0 commit comments

Comments
 (0)