Skip to content

Commit

Permalink
Fix parser_mode not inherited by nested parsers (#564)
Browse files Browse the repository at this point in the history
  • Loading branch information
mauvilsa authored Aug 20, 2024
1 parent 54ff57e commit cba25f1
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Fixed
<https://github.com/omni-us/jsonargparse/pull/560>`__).
- ``--print_shtab`` not adding file completer for ``_ActionConfigLoad`` (`#562
<https://github.com/omni-us/jsonargparse/pull/562>`__).
- ``parser_mode`` not inherited by nested parsers (`#564
<https://github.com/omni-us/jsonargparse/pull/564>`__).


v4.32.0 (2024-07-19)
Expand Down
2 changes: 1 addition & 1 deletion jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ def get_class_parser(val_class, sub_add_kwargs=None, skip_args=0):
if skip_args:
kwargs.setdefault("skip", set()).add(skip_args)
parser = parent_parser.get()
parser = type(parser)(exit_on_error=False, logger=parser.logger)
parser = type(parser)(exit_on_error=False, logger=parser.logger, parser_mode=parser.parser_mode)
remove_actions(parser, (ActionConfigFile, _ActionPrintConfig))
if inspect.isclass(val_class):
parser.add_class_arguments(val_class, **kwargs)
Expand Down
34 changes: 34 additions & 0 deletions jsonargparse_tests/test_loaders_dumpers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import os
from dataclasses import dataclass
from typing import List
from unittest.mock import patch

Expand Down Expand Up @@ -129,6 +130,39 @@ def test_load_value_dash():
assert " - " == load_value(" - ")


@dataclass
class CustomData:
fn: dict


class CustomContainer:
def __init__(self, data: CustomData):
self.data = data


def custom_loader(data):
data = yaml.safe_load(data)
if isinstance(data, dict) and "fn" in data:
data["fn"] = {k: custom_loader for k in data["fn"]}
return data


def custom_dumper(data):
if "data" in data and "fn" in data["data"]:
data["data"]["fn"] = {k: "dumped" for k in data["data"]["fn"]}
return yaml_dump(data)


def test_nested_parser_mode(parser):
set_loader("custom", custom_loader)
set_dumper("custom", custom_dumper)
parser.parser_mode = "custom"
parser.add_argument("--custom", type=CustomContainer)
cfg = parser.parse_args(['--custom.data={"fn": {"key": "value"}}'])
dump = yaml.safe_load(parser.dump(cfg))
assert dump["custom"]["init_args"]["data"] == {"fn": {"key": "dumped"}}


@pytest.mark.skipif(
not (omegaconf_support and "JSONARGPARSE_OMEGACONF_FULL_TEST" in os.environ),
reason="only for omegaconf as the yaml loader",
Expand Down

0 comments on commit cba25f1

Please sign in to comment.