Skip to content

Commit 2565ae7

Browse files
committed
Added .mypy_cache to .gitignore
Also: - Added a few more type hints
1 parent 6ba8d96 commit 2565ae7

File tree

4 files changed

+34
-29
lines changed

4 files changed

+34
-29
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,6 @@ htmlcov
1717

1818
# Visual Studio Code
1919
.vscode
20+
21+
# mypy optional static type checker
22+
.mypy_cache

cmd2/argparse_completer.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,16 @@ def my_completer(text: str, line: str, begidx: int, endidx:int, extra_param: str
8080

8181

8282
class CompletionItem(str):
83-
def __new__(cls, o, desc='', *args, **kwargs):
83+
def __new__(cls, o, desc='', *args, **kwargs) -> str:
8484
return str.__new__(cls, o, *args, **kwargs)
8585

8686
# noinspection PyMissingConstructor,PyUnusedLocal
87-
def __init__(self, o, desc='', *args, **kwargs):
87+
def __init__(self, o, desc='', *args, **kwargs) -> None:
8888
self.description = desc
8989

9090

9191
class _RangeAction(object):
92-
def __init__(self, nargs: Union[int, str, Tuple[int, int], None]):
92+
def __init__(self, nargs: Union[int, str, Tuple[int, int], None]) -> None:
9393
self.nargs_min = None
9494
self.nargs_max = None
9595

@@ -128,7 +128,7 @@ def __init__(self,
128128
choices=None,
129129
required=False,
130130
help=None,
131-
metavar=None):
131+
metavar=None) -> None:
132132

133133
_RangeAction.__init__(self, nargs)
134134

@@ -157,7 +157,7 @@ def __init__(self,
157157
choices=None,
158158
required=False,
159159
help=None,
160-
metavar=None):
160+
metavar=None) -> None:
161161

162162
_RangeAction.__init__(self, nargs)
163163

@@ -174,7 +174,7 @@ def __init__(self,
174174
metavar=metavar)
175175

176176

177-
def register_custom_actions(parser: argparse.ArgumentParser):
177+
def register_custom_actions(parser: argparse.ArgumentParser) -> None:
178178
"""Register custom argument action types"""
179179
parser.register('action', None, _StoreRangeAction)
180180
parser.register('action', 'store', _StoreRangeAction)
@@ -185,14 +185,14 @@ class AutoCompleter(object):
185185
"""Automatically command line tab completion based on argparse parameters"""
186186

187187
class _ArgumentState(object):
188-
def __init__(self):
188+
def __init__(self) -> None:
189189
self.min = None
190190
self.max = None
191191
self.count = 0
192192
self.needed = False
193193
self.variable = False
194194

195-
def reset(self):
195+
def reset(self) -> None:
196196
"""reset tracking values"""
197197
self.min = None
198198
self.max = None
@@ -206,7 +206,7 @@ def __init__(self,
206206
arg_choices: Dict[str, Union[List, Tuple, Callable]] = None,
207207
subcmd_args_lookup: dict = None,
208208
tab_for_arg_help: bool = True,
209-
cmd2_app=None):
209+
cmd2_app=None) -> None:
210210
"""
211211
Create an AutoCompleter
212212
@@ -439,7 +439,7 @@ def consume_positional_argument() -> None:
439439

440440
return completion_results
441441

442-
def _format_completions(self, action, completions: List[Union[str, CompletionItem]]):
442+
def _format_completions(self, action, completions: List[Union[str, CompletionItem]]) -> List[str]:
443443
if completions and len(completions) > 1 and isinstance(completions[0], CompletionItem):
444444
token_width = len(action.dest)
445445
completions_with_desc = []
@@ -665,7 +665,7 @@ def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against
665665
class ACHelpFormatter(argparse.HelpFormatter):
666666
"""Custom help formatter to configure ordering of help text"""
667667

668-
def _format_usage(self, usage, actions, groups, prefix):
668+
def _format_usage(self, usage, actions, groups, prefix) -> str:
669669
if prefix is None:
670670
prefix = _('Usage: ')
671671

@@ -778,7 +778,7 @@ def get_lines(parts, indent, prefix=None):
778778
# prefix with 'usage:'
779779
return '%s%s\n\n' % (prefix, usage)
780780

781-
def _format_action_invocation(self, action):
781+
def _format_action_invocation(self, action) -> str:
782782
if not action.option_strings:
783783
default = self._get_default_metavar_for_positional(action)
784784
metavar, = self._metavar_formatter(action, default)(1)
@@ -803,7 +803,7 @@ def _format_action_invocation(self, action):
803803
return ', '.join(action.option_strings) + ' ' + args_string
804804
# End cmd2 customization
805805

806-
def _metavar_formatter(self, action, default_metavar):
806+
def _metavar_formatter(self, action, default_metavar) -> Callable:
807807
if action.metavar is not None:
808808
result = action.metavar
809809
elif action.choices is not None:
@@ -822,7 +822,7 @@ def format(tuple_size):
822822
return (result, ) * tuple_size
823823
return format
824824

825-
def _format_args(self, action, default_metavar):
825+
def _format_args(self, action, default_metavar) -> str:
826826
get_metavar = self._metavar_formatter(action, default_metavar)
827827
# Begin cmd2 customization (less verbose)
828828
if isinstance(action, _RangeAction) and \
@@ -837,15 +837,15 @@ def _format_args(self, action, default_metavar):
837837
result = super()._format_args(action, default_metavar)
838838
return result
839839

840-
def _split_lines(self, text, width):
840+
def _split_lines(self, text: str, width) -> List[str]:
841841
return text.splitlines()
842842

843843

844844
# noinspection PyCompatibility
845845
class ACArgumentParser(argparse.ArgumentParser):
846846
"""Custom argparse class to override error method to change default help text."""
847847

848-
def __init__(self, *args, **kwargs):
848+
def __init__(self, *args, **kwargs) -> None:
849849
if 'formatter_class' not in kwargs:
850850
kwargs['formatter_class'] = ACHelpFormatter
851851

@@ -855,15 +855,15 @@ def __init__(self, *args, **kwargs):
855855
self._custom_error_message = ''
856856

857857
# Begin cmd2 customization
858-
def set_custom_message(self, custom_message=''):
858+
def set_custom_message(self, custom_message: str='') -> None:
859859
"""
860860
Allows an error message override to the error() function, useful when forcing a
861861
re-parse of arguments with newly required parameters
862862
"""
863863
self._custom_error_message = custom_message
864864
# End cmd2 customization
865865

866-
def error(self, message):
866+
def error(self, message: str) -> None:
867867
"""Custom error override. Allows application to control the error being displayed by argparse"""
868868
if len(self._custom_error_message) > 0:
869869
message = self._custom_error_message
@@ -884,7 +884,7 @@ def error(self, message):
884884
self.print_help()
885885
sys.exit(1)
886886

887-
def format_help(self):
887+
def format_help(self) -> str:
888888
"""Copy of format_help() from argparse.ArgumentParser with tweaks to separately display required parameters"""
889889
formatter = self._get_formatter()
890890

@@ -934,7 +934,7 @@ def format_help(self):
934934
# determine help from format above
935935
return formatter.format_help()
936936

937-
def _get_nargs_pattern(self, action):
937+
def _get_nargs_pattern(self, action) -> str:
938938
# Override _get_nargs_pattern behavior to use the nargs ranges provided by AutoCompleter
939939
if isinstance(action, _RangeAction) and \
940940
action.nargs_min is not None and action.nargs_max is not None:
@@ -947,7 +947,7 @@ def _get_nargs_pattern(self, action):
947947
return nargs_pattern
948948
return super(ACArgumentParser, self)._get_nargs_pattern(action)
949949

950-
def _match_argument(self, action, arg_strings_pattern):
950+
def _match_argument(self, action, arg_strings_pattern) -> int:
951951
# match the pattern for this action to the arg strings
952952
nargs_pattern = self._get_nargs_pattern(action)
953953
match = _re.match(nargs_pattern, arg_strings_pattern)
@@ -963,7 +963,7 @@ def _match_argument(self, action, arg_strings_pattern):
963963

964964
# This is the official python implementation with a 5 year old patch applied
965965
# See the comment below describing the patch
966-
def _parse_known_args(self, arg_strings, namespace): # pragma: no cover
966+
def _parse_known_args(self, arg_strings, namespace) -> Tuple[argparse.Namespace, List[str]]: # pragma: no cover
967967
# replace arg strings that are file references
968968
if self.fromfile_prefix_chars is not None:
969969
arg_strings = self._read_args_from_files(arg_strings)

cmd2/cmd2.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
import re
4040
import shlex
4141
import sys
42-
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
42+
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Union
4343

4444
import pyperclip
4545

@@ -940,7 +940,7 @@ def flag_based_complete(self, text: str, line: str, begidx: int, endidx: int,
940940
return completions_matches
941941

942942
def index_based_complete(self, text: str, line: str, begidx: int, endidx: int,
943-
index_dict: Dict[int, Union[Iterable, Callable]],
943+
index_dict: Mapping[int, Union[Iterable, Callable]],
944944
all_else: Union[None, Iterable, Callable] = None) -> List[str]:
945945
"""
946946
Tab completes based on a fixed position in the input string
@@ -1950,7 +1950,8 @@ def onecmd(self, statement: Statement) -> Optional[bool]:
19501950
"""
19511951
funcname = self._func_named(statement.command)
19521952
if not funcname:
1953-
return self.default(statement)
1953+
self.default(statement)
1954+
return
19541955

19551956
# Since we have a valid command store it in the history
19561957
if statement.command not in self.exclude_from_history:
@@ -1959,7 +1960,8 @@ def onecmd(self, statement: Statement) -> Optional[bool]:
19591960
try:
19601961
func = getattr(self, funcname)
19611962
except AttributeError:
1962-
return self.default(statement)
1963+
self.default(statement)
1964+
return
19631965

19641966
stop = func(statement)
19651967
return stop
@@ -2420,8 +2422,8 @@ def select(self, opts: Union[str, List[str], List[Tuple[str, Optional[str]]]], p
24202422
readline.remove_history_item(hlen - 1)
24212423

24222424
try:
2423-
response = int(response)
2424-
result = fulloptions[response - 1][0]
2425+
choice = int(response)
2426+
result = fulloptions[choice - 1][0]
24252427
break
24262428
except (ValueError, IndexError):
24272429
self.poutput("{!r} isn't a valid choice. Pick a number between 1 and {}:\n".format(response,

tests/test_cmd2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1309,7 +1309,7 @@ def test_select_invalid_option(select_app):
13091309
expected = normalize("""
13101310
1. sweet
13111311
2. salty
1312-
3 isn't a valid choice. Pick a number between 1 and 2:
1312+
'3' isn't a valid choice. Pick a number between 1 and 2:
13131313
{} with sweet sauce, yum!
13141314
""".format(food))
13151315

0 commit comments

Comments
 (0)