Skip to content

Commit 7dbd3a3

Browse files
committed
Fixed 'index out of range' error when passing no arguments to an argparse-based command function.
1 parent e4ab25f commit 7dbd3a3

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 2.5.9 (TBD)
2+
* Bug Fixes
3+
* Fixed 'index out of range' error when passing no arguments to an argparse-based command function.
4+
15
## 2.5.8 (December 17, 2024)
26
* Bug Fixes
37
* Rolled back undocumented changes to printing functions introduced in 2.5.0.

cmd2/decorators.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def _parse_positionals(args: Tuple[Any, ...]) -> Tuple['cmd2.Cmd', Union[Stateme
9191
Cmd,
9292
)
9393

94-
if (isinstance(arg, Cmd) or isinstance(arg, CommandSet)) and len(args) > pos:
94+
if isinstance(arg, (Cmd, CommandSet)) and len(args) > pos + 1:
9595
if isinstance(arg, CommandSet):
9696
arg = arg._cmd
9797
next_arg = args[pos + 1]
@@ -100,7 +100,7 @@ def _parse_positionals(args: Tuple[Any, ...]) -> Tuple['cmd2.Cmd', Union[Stateme
100100

101101
# This shouldn't happen unless we forget to pass statement in `Cmd.onecmd` or
102102
# somehow call the unbound class method.
103-
raise TypeError('Expected arguments: cmd: cmd2.Cmd, statement: Union[Statement, str] Not found') # pragma: no cover
103+
raise TypeError('Expected arguments: cmd: cmd2.Cmd, statement: Union[Statement, str] Not found')
104104

105105

106106
def _arg_swap(args: Union[Sequence[Any]], search_arg: Any, *replace_arg: Any) -> List[Any]:

tests/test_argparse.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,13 @@ def test_argparse_remove_quotes(argparse_app):
148148
assert out == ['hello there']
149149

150150

151+
def test_argparse_with_no_args(argparse_app):
152+
"""Make sure we receive TypeError when calling argparse-based function with no args"""
153+
with pytest.raises(TypeError) as excinfo:
154+
argparse_app.do_say()
155+
assert 'Expected arguments' in str(excinfo.value)
156+
157+
151158
def test_argparser_kwargs(argparse_app, capsys):
152159
"""Test with_argparser wrapper passes through kwargs to command function"""
153160
argparse_app.do_say('word', keyword_arg="foo")

0 commit comments

Comments
 (0)