1
+ # coding=utf-8
1
2
"""
2
3
This module adds capabilities to argparse by patching a few of its functions.
3
4
It also defines a parser class called Cmd2ArgumentParser which improves error
@@ -229,17 +230,24 @@ def my_completer(self, text, line, begidx, endidx, arg_tokens)
229
230
ZERO_OR_MORE ,
230
231
ArgumentError ,
231
232
)
232
- from collections .abc import Callable , Iterable , Sequence
233
233
from gettext import (
234
234
gettext ,
235
235
)
236
236
from typing import (
237
237
IO ,
238
238
TYPE_CHECKING ,
239
239
Any ,
240
+ Callable ,
241
+ Dict ,
242
+ Iterable ,
243
+ List ,
240
244
NoReturn ,
241
245
Optional ,
242
246
Protocol ,
247
+ Sequence ,
248
+ Set ,
249
+ Tuple ,
250
+ Type ,
243
251
Union ,
244
252
cast ,
245
253
runtime_checkable ,
@@ -317,7 +325,7 @@ class ChoicesProviderFuncBase(Protocol):
317
325
Function that returns a list of choices in support of tab completion
318
326
"""
319
327
320
- def __call__ (self ) -> list [str ]: ... # pragma: no cover
328
+ def __call__ (self ) -> List [str ]: ... # pragma: no cover
321
329
322
330
323
331
@runtime_checkable
@@ -326,7 +334,7 @@ class ChoicesProviderFuncWithTokens(Protocol):
326
334
Function that returns a list of choices in support of tab completion and accepts a dictionary of prior arguments.
327
335
"""
328
336
329
- def __call__ (self , * , arg_tokens : dict [str , list [str ]] = {}) -> list [str ]: ... # pragma: no cover
337
+ def __call__ (self , * , arg_tokens : Dict [str , List [str ]] = {}) -> List [str ]: ... # pragma: no cover
330
338
331
339
332
340
ChoicesProviderFunc = Union [ChoicesProviderFuncBase , ChoicesProviderFuncWithTokens ]
@@ -344,7 +352,7 @@ def __call__(
344
352
line : str ,
345
353
begidx : int ,
346
354
endidx : int ,
347
- ) -> list [str ]: ... # pragma: no cover
355
+ ) -> List [str ]: ... # pragma: no cover
348
356
349
357
350
358
@runtime_checkable
@@ -361,8 +369,8 @@ def __call__(
361
369
begidx : int ,
362
370
endidx : int ,
363
371
* ,
364
- arg_tokens : dict [str , list [str ]] = {},
365
- ) -> list [str ]: ... # pragma: no cover
372
+ arg_tokens : Dict [str , List [str ]] = {},
373
+ ) -> List [str ]: ... # pragma: no cover
366
374
367
375
368
376
CompleterFunc = Union [CompleterFuncBase , CompleterFuncWithTokens ]
@@ -563,7 +571,7 @@ def _action_set_descriptive_header(self: argparse.Action, descriptive_header: Op
563
571
############################################################################################################
564
572
# Patch argparse.Action with accessors for nargs_range attribute
565
573
############################################################################################################
566
- def _action_get_nargs_range (self : argparse .Action ) -> Optional [tuple [int , Union [int , float ]]]:
574
+ def _action_get_nargs_range (self : argparse .Action ) -> Optional [Tuple [int , Union [int , float ]]]:
567
575
"""
568
576
Get the nargs_range attribute of an argparse Action.
569
577
@@ -574,13 +582,13 @@ def _action_get_nargs_range(self: argparse.Action) -> Optional[tuple[int, Union[
574
582
:param self: argparse Action being queried
575
583
:return: The value of nargs_range or None if attribute does not exist
576
584
"""
577
- return cast ("Optional[tuple [int, Union[int, float]]]" , getattr (self , ATTR_NARGS_RANGE , None ))
585
+ return cast ("Optional[Tuple [int, Union[int, float]]]" , getattr (self , ATTR_NARGS_RANGE , None ))
578
586
579
587
580
588
setattr (argparse .Action , 'get_nargs_range' , _action_get_nargs_range )
581
589
582
590
583
- def _action_set_nargs_range (self : argparse .Action , nargs_range : Optional [tuple [int , Union [int , float ]]]) -> None :
591
+ def _action_set_nargs_range (self : argparse .Action , nargs_range : Optional [Tuple [int , Union [int , float ]]]) -> None :
584
592
"""
585
593
Set the nargs_range attribute of an argparse Action.
586
594
@@ -638,11 +646,11 @@ def _action_set_suppress_tab_hint(self: argparse.Action, suppress_tab_hint: bool
638
646
# Allow developers to add custom action attributes
639
647
############################################################################################################
640
648
641
- CUSTOM_ACTION_ATTRIBS : set [str ] = set ()
649
+ CUSTOM_ACTION_ATTRIBS : Set [str ] = set ()
642
650
_CUSTOM_ATTRIB_PFX = '_attr_'
643
651
644
652
645
- def register_argparse_argument_parameter (param_name : str , param_type : Optional [type [Any ]]) -> None :
653
+ def register_argparse_argument_parameter (param_name : str , param_type : Optional [Type [Any ]]) -> None :
646
654
"""
647
655
Registers a custom argparse argument parameter.
648
656
@@ -711,7 +719,7 @@ def _action_set_custom_parameter(self: argparse.Action, value: Any) -> None:
711
719
def _add_argument_wrapper (
712
720
self : argparse ._ActionsContainer ,
713
721
* args : Any ,
714
- nargs : Union [int , str , tuple [int ], tuple [int , int ], tuple [int , float ], None ] = None ,
722
+ nargs : Union [int , str , Tuple [int ], Tuple [int , int ], Tuple [int , float ], None ] = None ,
715
723
choices_provider : Optional [ChoicesProviderFunc ] = None ,
716
724
completer : Optional [CompleterFunc ] = None ,
717
725
suppress_tab_hint : bool = False ,
@@ -762,7 +770,7 @@ def _add_argument_wrapper(
762
770
nargs_range = None
763
771
764
772
if nargs is not None :
765
- nargs_adjusted : Union [int , str , tuple [int ], tuple [int , int ], tuple [int , float ], None ]
773
+ nargs_adjusted : Union [int , str , Tuple [int ], Tuple [int , int ], Tuple [int , float ], None ]
766
774
# Check if nargs was given as a range
767
775
if isinstance (nargs , tuple ):
768
776
# Handle 1-item tuple by setting max to INFINITY
@@ -812,7 +820,7 @@ def _add_argument_wrapper(
812
820
kwargs ['nargs' ] = nargs_adjusted
813
821
814
822
# Extract registered custom keyword arguments
815
- custom_attribs : dict [str , Any ] = {}
823
+ custom_attribs : Dict [str , Any ] = {}
816
824
for keyword , value in kwargs .items ():
817
825
if keyword in CUSTOM_ACTION_ATTRIBS :
818
826
custom_attribs [keyword ] = value
@@ -910,7 +918,7 @@ def _match_argument_wrapper(self: argparse.ArgumentParser, action: argparse.Acti
910
918
ATTR_AP_COMPLETER_TYPE = 'ap_completer_type'
911
919
912
920
913
- def _ArgumentParser_get_ap_completer_type (self : argparse .ArgumentParser ) -> Optional [type ['ArgparseCompleter' ]]:
921
+ def _ArgumentParser_get_ap_completer_type (self : argparse .ArgumentParser ) -> Optional [Type ['ArgparseCompleter' ]]:
914
922
"""
915
923
Get the ap_completer_type attribute of an argparse ArgumentParser.
916
924
@@ -921,13 +929,13 @@ def _ArgumentParser_get_ap_completer_type(self: argparse.ArgumentParser) -> Opti
921
929
:param self: ArgumentParser being queried
922
930
:return: An ArgparseCompleter-based class or None if attribute does not exist
923
931
"""
924
- return cast ("Optional[type [ArgparseCompleter]]" , getattr (self , ATTR_AP_COMPLETER_TYPE , None ))
932
+ return cast ("Optional[Type [ArgparseCompleter]]" , getattr (self , ATTR_AP_COMPLETER_TYPE , None ))
925
933
926
934
927
935
setattr (argparse .ArgumentParser , 'get_ap_completer_type' , _ArgumentParser_get_ap_completer_type )
928
936
929
937
930
- def _ArgumentParser_set_ap_completer_type (self : argparse .ArgumentParser , ap_completer_type : type ['ArgparseCompleter' ]) -> None :
938
+ def _ArgumentParser_set_ap_completer_type (self : argparse .ArgumentParser , ap_completer_type : Type ['ArgparseCompleter' ]) -> None :
931
939
"""
932
940
Set the ap_completer_type attribute of an argparse ArgumentParser.
933
941
@@ -1084,9 +1092,9 @@ def _format_usage(
1084
1092
# End cmd2 customization
1085
1093
1086
1094
# helper for wrapping lines
1087
- def get_lines (parts : list [str ], indent : str , prefix : Optional [str ] = None ) -> list [str ]:
1088
- lines : list [str ] = []
1089
- line : list [str ] = []
1095
+ def get_lines (parts : List [str ], indent : str , prefix : Optional [str ] = None ) -> List [str ]:
1096
+ lines : List [str ] = []
1097
+ line : List [str ] = []
1090
1098
if prefix is not None :
1091
1099
line_len = len (prefix ) - 1
1092
1100
else :
@@ -1147,7 +1155,7 @@ def _format_action_invocation(self, action: argparse.Action) -> str:
1147
1155
(metavar ,) = self ._metavar_formatter (action , default )(1 )
1148
1156
return metavar
1149
1157
1150
- parts : list [str ] = []
1158
+ parts : List [str ] = []
1151
1159
1152
1160
# if the Optional doesn't take a value, format is:
1153
1161
# -s, --long
@@ -1167,8 +1175,8 @@ def _format_action_invocation(self, action: argparse.Action) -> str:
1167
1175
def _determine_metavar (
1168
1176
self ,
1169
1177
action : argparse .Action ,
1170
- default_metavar : Union [str , tuple [str , ...]],
1171
- ) -> Union [str , tuple [str , ...]]:
1178
+ default_metavar : Union [str , Tuple [str , ...]],
1179
+ ) -> Union [str , Tuple [str , ...]]:
1172
1180
"""Custom method to determine what to use as the metavar value of an action"""
1173
1181
if action .metavar is not None :
1174
1182
result = action .metavar
@@ -1184,18 +1192,18 @@ def _determine_metavar(
1184
1192
def _metavar_formatter (
1185
1193
self ,
1186
1194
action : argparse .Action ,
1187
- default_metavar : Union [str , tuple [str , ...]],
1188
- ) -> Callable [[int ], tuple [str , ...]]:
1195
+ default_metavar : Union [str , Tuple [str , ...]],
1196
+ ) -> Callable [[int ], Tuple [str , ...]]:
1189
1197
metavar = self ._determine_metavar (action , default_metavar )
1190
1198
1191
- def format_tuple (tuple_size : int ) -> tuple [str , ...]:
1199
+ def format_tuple (tuple_size : int ) -> Tuple [str , ...]:
1192
1200
if isinstance (metavar , tuple ):
1193
1201
return metavar
1194
1202
return (metavar ,) * tuple_size
1195
1203
1196
1204
return format_tuple
1197
1205
1198
- def _format_args (self , action : argparse .Action , default_metavar : Union [str , tuple [str , ...]]) -> str :
1206
+ def _format_args (self , action : argparse .Action , default_metavar : Union [str , Tuple [str , ...]]) -> str :
1199
1207
"""Customized to handle ranged nargs and make other output less verbose"""
1200
1208
metavar = self ._determine_metavar (action , default_metavar )
1201
1209
metavar_formatter = self ._metavar_formatter (action , default_metavar )
@@ -1233,7 +1241,7 @@ def __init__(
1233
1241
description : Optional [str ] = None ,
1234
1242
epilog : Optional [str ] = None ,
1235
1243
parents : Sequence [argparse .ArgumentParser ] = (),
1236
- formatter_class : type [argparse .HelpFormatter ] = Cmd2HelpFormatter ,
1244
+ formatter_class : Type [argparse .HelpFormatter ] = Cmd2HelpFormatter ,
1237
1245
prefix_chars : str = '-' ,
1238
1246
fromfile_prefix_chars : Optional [str ] = None ,
1239
1247
argument_default : Optional [str ] = None ,
@@ -1244,7 +1252,7 @@ def __init__(
1244
1252
suggest_on_error : bool = False ,
1245
1253
color : bool = False ,
1246
1254
* ,
1247
- ap_completer_type : Optional [type ['ArgparseCompleter' ]] = None ,
1255
+ ap_completer_type : Optional [Type ['ArgparseCompleter' ]] = None ,
1248
1256
) -> None :
1249
1257
"""
1250
1258
# Custom parameter added by cmd2
@@ -1402,10 +1410,10 @@ def set(self, new_val: Any) -> None:
1402
1410
1403
1411
1404
1412
# The default ArgumentParser class for a cmd2 app
1405
- DEFAULT_ARGUMENT_PARSER : type [argparse .ArgumentParser ] = Cmd2ArgumentParser
1413
+ DEFAULT_ARGUMENT_PARSER : Type [argparse .ArgumentParser ] = Cmd2ArgumentParser
1406
1414
1407
1415
1408
- def set_default_argument_parser_type (parser_type : type [argparse .ArgumentParser ]) -> None :
1416
+ def set_default_argument_parser_type (parser_type : Type [argparse .ArgumentParser ]) -> None :
1409
1417
"""
1410
1418
Set the default ArgumentParser class for a cmd2 app. This must be called prior to loading cmd2.py if
1411
1419
you want to override the parser for cmd2's built-in commands. See examples/override_parser.py.
0 commit comments