Skip to content

Commit d389da9

Browse files
committed
Tests for namespace nested parameter
1 parent 1dccf55 commit d389da9

2 files changed

Lines changed: 35 additions & 5 deletions

File tree

‎jsonargparse/_namespace.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -236,22 +236,20 @@ def as_flat(self) -> argparse.Namespace:
236236
def items(self, branches: bool = False, nested: bool = True) -> Iterator[Tuple[str, Any]]:
237237
"""Returns a generator of all leaf (key, value) items, optionally including branches."""
238238
for key, val in vars(self).items():
239-
if not nested and "." in key:
240-
continue
241239
key = del_clash_mark(key)
242240
if isinstance(val, Namespace):
243241
if branches:
244242
yield key, val
243+
if not nested:
244+
continue
245245
for subkey, subval in val.items(branches):
246246
yield key + "." + del_clash_mark(subkey), subval
247247
else:
248248
yield key, val
249249

250250
def keys(self, branches: bool = False, nested: bool = True) -> Iterator[str]:
251251
"""Returns a generator of all leaf keys, optionally including branches."""
252-
for key, _ in self.items(branches):
253-
if not nested and "." in key:
254-
continue
252+
for key, _ in self.items(branches=branches, nested=nested):
255253
yield key
256254

257255
def values(self, branches: bool = False) -> Iterator[Any]:

‎jsonargparse_tests/test_namespace.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,3 +296,35 @@ def test_add_argument_meta_key_error(meta_key, parser):
296296
with pytest.raises(ValueError) as ctx:
297297
parser.add_argument(meta_key)
298298
ctx.match(f'"{meta_key}" not allowed')
299+
300+
301+
def test_items_branches_nested():
302+
ns = Namespace()
303+
ns["a.b"] = 1
304+
ns["a.c"] = 2
305+
ns["d"] = 3
306+
307+
items = list(ns.items(branches=True))
308+
assert items == [("a", Namespace(b=1, c=2)), ("a.b", 1), ("a.c", 2), ("d", 3)]
309+
310+
items = list(ns.items(branches=True, nested=False))
311+
assert items == [("a", Namespace(b=1, c=2)), ("d", 3)]
312+
313+
items = list(ns.items(nested=False))
314+
assert items == [("d", 3)]
315+
316+
317+
def test_keys_branches_nested():
318+
ns = Namespace()
319+
ns["a.b"] = 1
320+
ns["a.c"] = 2
321+
ns["d"] = 3
322+
323+
keys = list(ns.keys(branches=True))
324+
assert keys == ["a", "a.b", "a.c", "d"]
325+
326+
keys = list(ns.keys(branches=True, nested=False))
327+
assert keys == ["a", "d"]
328+
329+
keys = list(ns.keys(nested=False))
330+
assert keys == ["d"]

0 commit comments

Comments
 (0)