Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional subcommands fail with a KeyError #68

Closed
carmocca opened this issue Aug 3, 2021 · 1 comment
Closed

Optional subcommands fail with a KeyError #68

carmocca opened this issue Aug 3, 2021 · 1 comment
Labels
bug Something isn't working

Comments

@carmocca
Copy link
Contributor

carmocca commented Aug 3, 2021

from jsonargparse import ArgumentParser

parser = ArgumentParser()
subcommands = parser.add_subcommands(required=False)
subparser = ArgumentParser()
subcommands.add_subcommand('foo', subparser)
parser.parse_args()

When called with no subcommand, prints:

Error: None

After some debugging, I found two issues:

(1):

subparser = action._name_parser_map[subcommand]

should be replaced with

        subparser = action._name_parser_map.get(subcommand)
        if subparser is None:
            return

(2):

KeyErrors should not be catched here:

except (TypeError, KeyError) as ex:
self.error(str(ex), ex)

which hides the original exception when it seems to be an actual bug:

Traceback (most recent call last):
  File "/Users/carlosmocholi/Library/Application Support/JetBrains/PyCharmCE2020.3/scratches/scratch_12.py", line 8, in <module>
    parser.parse_args()
  File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/core.py", line 385, in parse_args
    parsed_cfg = self._parse_common(
  File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/core.py", line 308, in _parse_common
    _ActionSubCommands.handle_subcommands(self, cfg, env=env, defaults=defaults, fail_no_subcommand=fail_no_subcommand)
  File "/Users/carlosmocholi/.pyenv/versions/3.9.1/envs/lightning-3.9/lib/python3.9/site-packages/jsonargparse/actions.py", line 767, in handle_subcommands
    subparser = action._name_parser_map[subcommand]
KeyError: None
@mauvilsa mauvilsa added the bug Something isn't working label Aug 3, 2021
mauvilsa added a commit that referenced this issue Aug 16, 2021
…gument.

- Don't ignore ``KeyError`` in call to instantiate_classes #81.
- Fixed optional subcommands fail with a KeyError #68.
@mauvilsa
Copy link
Member

The fix is now in master.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants