Skip to content

Commit c852274

Browse files
committed
Fixed add_subcommands failure when parser has required argument and default config available #232.
1 parent 89f88de commit c852274

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

CHANGELOG.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ paths are considered internals and can change in minor and patch releases.
1515
v4.20.0 (2023-01-??)
1616
--------------------
1717

18+
Fixed
19+
^^^^^
20+
- ``add_subcommands`` fails when parser has required argument and default config
21+
available `#232 <https://github.com/omni-us/jsonargparse/issues/232>`__.
22+
1823
Changed
1924
^^^^^^^
2025
- When parsing fails now ``argparse.ArgumentError`` is raised instead of

jsonargparse/core.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,7 @@ def add_subcommands(self, required: bool = True, dest: str = 'subcommand', **kwa
670670
"""
671671
if 'description' not in kwargs:
672672
kwargs['description'] = 'For more details of each subcommand, add it as an argument followed by --help.'
673-
with parser_context(parent_parser=self):
673+
with parser_context(parent_parser=self, lenient_check=True):
674674
subcommands: _ActionSubCommands = super().add_subparsers(dest=dest, **kwargs) # type: ignore
675675
if required:
676676
self.required_args.add(dest)

jsonargparse_tests/test_core.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import json
44
import os
5+
import pathlib
56
import pickle
67
import sys
78
import unittest
@@ -1012,6 +1013,19 @@ def test_get_default_with_multiple_default_config_files(self):
10121013
self.assertIn('defaults_2.yaml', out.getvalue())
10131014

10141015

1016+
def test_required_arg_in_default_config_and_add_subcommands(self):
1017+
pathlib.Path('config.yaml').write_text('output: test\nprepare:\n media: test\n')
1018+
parser = ArgumentParser(default_config_files=['config.yaml'])
1019+
parser.add_argument('--output', required=True)
1020+
subcommands = parser.add_subcommands()
1021+
prepare = ArgumentParser()
1022+
prepare.add_argument('--media', required=True)
1023+
subcommands.add_subcommand('prepare', prepare)
1024+
cfg = parser.parse_args([])
1025+
self.assertEqual(str(cfg.__default_config__), 'config.yaml')
1026+
self.assertEqual(strip_meta(cfg), Namespace(output='test', prepare=Namespace(media='test'), subcommand='prepare'))
1027+
1028+
10151029
def test_ActionConfigFile(self):
10161030
os.mkdir(os.path.join(self.tmpdir, 'subdir'))
10171031
rel_yaml_file = os.path.join('subdir', 'config.yaml')

0 commit comments

Comments
 (0)