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