Skip to content

Commit cba25f1

Browse files
authored
Fix parser_mode not inherited by nested parsers (#564)
1 parent 54ff57e commit cba25f1

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ Fixed
2323
<https://github.com/omni-us/jsonargparse/pull/560>`__).
2424
- ``--print_shtab`` not adding file completer for ``_ActionConfigLoad`` (`#562
2525
<https://github.com/omni-us/jsonargparse/pull/562>`__).
26+
- ``parser_mode`` not inherited by nested parsers (`#564
27+
<https://github.com/omni-us/jsonargparse/pull/564>`__).
2628

2729

2830
v4.32.0 (2024-07-19)

jsonargparse/_typehints.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -615,7 +615,7 @@ def get_class_parser(val_class, sub_add_kwargs=None, skip_args=0):
615615
if skip_args:
616616
kwargs.setdefault("skip", set()).add(skip_args)
617617
parser = parent_parser.get()
618-
parser = type(parser)(exit_on_error=False, logger=parser.logger)
618+
parser = type(parser)(exit_on_error=False, logger=parser.logger, parser_mode=parser.parser_mode)
619619
remove_actions(parser, (ActionConfigFile, _ActionPrintConfig))
620620
if inspect.isclass(val_class):
621621
parser.add_class_arguments(val_class, **kwargs)

jsonargparse_tests/test_loaders_dumpers.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import os
4+
from dataclasses import dataclass
45
from typing import List
56
from unittest.mock import patch
67

@@ -129,6 +130,39 @@ def test_load_value_dash():
129130
assert " - " == load_value(" - ")
130131

131132

133+
@dataclass
134+
class CustomData:
135+
fn: dict
136+
137+
138+
class CustomContainer:
139+
def __init__(self, data: CustomData):
140+
self.data = data
141+
142+
143+
def custom_loader(data):
144+
data = yaml.safe_load(data)
145+
if isinstance(data, dict) and "fn" in data:
146+
data["fn"] = {k: custom_loader for k in data["fn"]}
147+
return data
148+
149+
150+
def custom_dumper(data):
151+
if "data" in data and "fn" in data["data"]:
152+
data["data"]["fn"] = {k: "dumped" for k in data["data"]["fn"]}
153+
return yaml_dump(data)
154+
155+
156+
def test_nested_parser_mode(parser):
157+
set_loader("custom", custom_loader)
158+
set_dumper("custom", custom_dumper)
159+
parser.parser_mode = "custom"
160+
parser.add_argument("--custom", type=CustomContainer)
161+
cfg = parser.parse_args(['--custom.data={"fn": {"key": "value"}}'])
162+
dump = yaml.safe_load(parser.dump(cfg))
163+
assert dump["custom"]["init_args"]["data"] == {"fn": {"key": "dumped"}}
164+
165+
132166
@pytest.mark.skipif(
133167
not (omegaconf_support and "JSONARGPARSE_OMEGACONF_FULL_TEST" in os.environ),
134168
reason="only for omegaconf as the yaml loader",

0 commit comments

Comments
 (0)