Skip to content

Commit 3ae71e8

Browse files
authored
Merge pull request #440 from python-cmd2/type_hinting
Improve type hinting
2 parents 1bcf598 + 44282fa commit 3ae71e8

File tree

8 files changed

+310
-291
lines changed

8 files changed

+310
-291
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/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#
22
# -*- coding: utf-8 -*-
3+
"""This simply imports certain things for backwards compatibility."""
34
from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
45
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category

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)

0 commit comments

Comments
 (0)