Skip to content
This repository has been archived by the owner on Nov 3, 2023. It is now read-only.

Commit

Permalink
[parser] Support nargs=+ in parse_kwargs (#3930)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenroller authored Aug 13, 2021
1 parent 70ee4a2 commit cdc8c05
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions parlai/core/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")

Expand Down Expand Up @@ -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}")

Expand Down
19 changes: 19 additions & 0 deletions tests/test_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit cdc8c05

Please sign in to comment.