From cdc8c05c0cfdd1fb0f750142a575c46ec7a726de Mon Sep 17 00:00:00 2001 From: Stephen Roller Date: Fri, 13 Aug 2021 16:06:13 -0400 Subject: [PATCH] [parser] Support nargs=+ in parse_kwargs (#3930) --- parlai/core/params.py | 4 ++-- tests/test_params.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/parlai/core/params.py b/parlai/core/params.py index bd5241ef848..bfd982c16aa 100644 --- a/parlai/core/params.py +++ b/parlai/core/params.py @@ -1223,7 +1223,7 @@ def _kwargs_to_str_args(self, **kwargs): string_args.append(self._value2argstr(value)) elif isinstance(action, argparse._StoreAction) and action.nargs in '*+': string_args.append(last_option_string) - string_args.extend([self._value2argstr(value) for v in value]) + string_args.extend([self._value2argstr(v) for v in value]) else: raise TypeError(f"Don't know what to do with {action}") @@ -1262,7 +1262,7 @@ def _kwargs_to_str_args(self, **kwargs): elif isinstance(action, argparse._StoreAction) and action.nargs in '*+': string_args.append(last_option_string) # Special case: Labels - string_args.extend([str(v) for v in value]) + string_args.extend([self._value2argstr(v) for v in value]) else: raise TypeError(f"Don't know what to do with {action}") diff --git a/tests/test_params.py b/tests/test_params.py index bae2c3fdca5..c5505b319ff 100644 --- a/tests/test_params.py +++ b/tests/test_params.py @@ -190,6 +190,25 @@ def test_parse_kwargs_multirounds(self): with self.assertRaises(KeyError): parser.parse_kwargs(task='integration_tests', fake_option=False) + def test_parse_kwargs_nargsplus(self): + """ + Test parse_kwargs when provided an argument with >1 item + """ + parser = ParlaiParser(False, False) + parser.add_argument('--example', nargs='+', choices=['a', 'b', 'c']) + opt = parser.parse_args(['--example', 'a', 'b']) + assert opt['example'] == ['a', 'b'] + + parser = ParlaiParser(False, False) + parser.add_argument('--example', nargs='+', choices=['a', 'b', 'c']) + opt = parser.parse_kwargs(example=['a', 'b']) + assert opt['example'] == ['a', 'b'] + + parser = ParlaiParser(False, False) + parser.add_argument('--example', nargs='+') + opt = parser.parse_kwargs(example=['x', 'y']) + assert opt['example'] == ['x', 'y'] + def test_bool(self): """ test add_argument(type=bool)