Skip to content

Commit 42e9c0a

Browse files
committed
Fixed failure when setting individual dict key values for subclasses and .init_args. is included in argument #251.
1 parent 3de6d6f commit 42e9c0a

File tree

3 files changed

+27
-6
lines changed

3 files changed

+27
-6
lines changed

CHANGELOG.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Fixed
2424
contexts `#247 <https://github.com/omni-us/jsonargparse/issues/247>`__.
2525
- Failure with dataclasses that have field with ``init=False`` `#252
2626
<https://github.com/omni-us/jsonargparse/issues/252>`__.
27+
- Failure when setting individual dict key values for subclasses and
28+
``.init_args.`` is included in argument `#251
29+
<https://github.com/omni-us/jsonargparse/issues/251>`__.
2730

2831

2932
v4.20.0 (2023-02-20)

jsonargparse/typehints.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,10 @@ def __call__(self, *args, **kwargs):
394394
cfg, val, opt_str = args[1:]
395395
if not (self.nargs == '?' and val is None):
396396
if isinstance(opt_str, str) and opt_str.startswith(f'--{self.dest}.'):
397-
sub_opt = opt_str[len(f'--{self.dest}.'):]
397+
if opt_str.startswith(f'--{self.dest}.init_args.'):
398+
sub_opt = opt_str[len(f'--{self.dest}.init_args.'):]
399+
else:
400+
sub_opt = opt_str[len(f'--{self.dest}.'):]
398401
val = NestedArg(key=sub_opt, val=val)
399402
append = opt_str == f'--{self.dest}+'
400403
val = self._check_type(val, append=append, cfg=cfg)
@@ -806,11 +809,7 @@ def subclass_spec_as_namespace(val, prev_val=None):
806809
if '.' not in key:
807810
root_key = key
808811
else:
809-
if key.startswith('init_args.'):
810-
root_key = 'init_args'
811-
key = key[len('init_args.'):]
812-
val = Namespace({key: val})
813-
elif key.startswith('dict_kwargs.'):
812+
if key.startswith('dict_kwargs.'):
814813
root_key = 'dict_kwargs'
815814
key = key[len('dict_kwargs.'):]
816815
val = {key: val}

jsonargparse_tests/test_typehints.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,25 @@ def test_dict_items(self):
230230
self.assertEqual(cfg.dict, {'one': 1, 'two': 2})
231231

232232

233+
def test_subclass_dict_items(self):
234+
class Class:
235+
def __init__(self, param: Dict[str, int]):
236+
pass
237+
238+
parser = ArgumentParser(exit_on_error=False)
239+
parser.add_argument('--val', type=Class)
240+
241+
with mock_module(Class) as module:
242+
for init_args in ['', '.init_args']:
243+
cfg = parser.parse_args([
244+
f'--val={module}.Class',
245+
f'--val{init_args}.param.one=1',
246+
f'--val{init_args}.param.two=2',
247+
])
248+
self.assertEqual(cfg.val.class_path, f'{module}.Class')
249+
self.assertEqual(cfg.val.init_args.param, {'one': 1, 'two': 2})
250+
251+
233252
def test_dict_union(self):
234253
class MyEnum(Enum):
235254
ab = 1

0 commit comments

Comments
 (0)