Skip to content

Commit

Permalink
Allow discard_init_args_on_class_path_change to handle more nested …
Browse files Browse the repository at this point in the history
…contexts (#248)

* allow `discard_init_args_on_class_path_change` to handle more nested contexts

* Further extend contexts handled by ``discard_init_args_on_class_path_change``

Co-authored-by: Mauricio Villegas <[email protected]>

* update changelog

---------

Co-authored-by: Mauricio Villegas <[email protected]>
  • Loading branch information
speediedan and mauvilsa authored Mar 9, 2023
1 parent 14b4842 commit 1fce989
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
5 changes: 4 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@ The semantic versioning only considers the public API as described in
paths are considered internals and can change in minor and patch releases.


v4.20.1 (2023-02-??)
v4.20.1 (2023-03-??)
--------------------

Fixed
^^^^^
- Allow ``discard_init_args_on_class_path_change`` to handle more nested contexts `#247
<https://github.com/omni-us/jsonargparse/issues/247>`__.

- Dump not working for partial callable with return instance
`pytorch-lightning#15340 (comment)
<https://github.com/Lightning-AI/lightning/issues/15340#issuecomment-1439203008>`__.
Expand Down
1 change: 1 addition & 0 deletions jsonargparse/typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,7 @@ def discard_init_args_on_class_path_change(parser_or_action, prev_val, value):
sub_add_kwargs = getattr(parser_or_action, 'sub_add_kwargs', {})
parser = ActionTypeHint.get_class_parser(value['class_path'], sub_add_kwargs)
del_args = {}
prev_val = subclass_spec_as_namespace(prev_val)
for key, val in list(prev_val.init_args.__dict__.items()):
action = _find_action(parser, key)
if action:
Expand Down
40 changes: 40 additions & 0 deletions jsonargparse_tests/test_signatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,46 @@ def __init__(self, sub: Base = lazy_instance(Sub1)) -> None:
self.assertIsInstance(init.main.sub, Sub2)
self.assertTrue(any("discarding init_args: {'s1': 'x'}" in o for o in log.output))

def test_config_nested_dict_discard_init_args(self):
class Base:
def __init__(self, b: float = 0.5):
pass

class Sub1(Base):
def __init__(self, s1: int = 3, **kwargs):
super().__init__(**kwargs)

class Sub2(Base):
def __init__(self, s2: int = 4, **kwargs):
super().__init__(**kwargs)

class Main:
def __init__(self, sub: Optional[Dict] = None) -> None:
self.sub = sub

configs, subconfigs, config_paths = {}, {}, {}
with mock_module(Base, Sub1, Sub2, Main) as module:
parser = ArgumentParser(exit_on_error=False, logger={'level': 'DEBUG'})
parser.add_argument('--config', action=ActionConfigFile)
parser.add_subclass_arguments(Main, 'main')
parser.set_defaults(main=lazy_instance(Main))
for c in [1, 2]:
subconfigs[c] = {
'sub': {
'class_path': f'{module}.Sub{c}',
'init_args': {f's{c}': c},
}
}
configs[c] = {'main': {'class_path': f'{module}.Main','init_args': subconfigs[c],}}
config_paths[c] = Path(f'config{c}.yaml')
config_paths[c].write_text(yaml.safe_dump(configs[c]))

with self.assertLogs(logger=parser.logger, level='DEBUG') as log:
cfg = parser.parse_args([f'--config={config_paths[1]}', f'--config={config_paths[2]}'])
init = parser.instantiate_classes(cfg)
self.assertIsInstance(init.main, Main)
self.assertTrue(init.main.sub['init_args']['s2'], 2)
self.assertTrue(any("discarding init_args: {'s1': 1}" in o for o in log.output))

@dataclasses.dataclass(frozen=True)
class MyDataClassA:
Expand Down

0 comments on commit 1fce989

Please sign in to comment.