106106# Utility functions and classes
107107# =============================
108108
109+
109110class _AttributeHolder (object ):
110111 """Abstract base class that provides __repr__.
111112
@@ -175,7 +176,7 @@ def __init__(
175176 width = shutil .get_terminal_size ().columns
176177 width -= 2
177178
178- self ._set_color ( color )
179+ self ._color = color
179180 self ._prog = prog
180181 self ._indent_increment = indent_increment
181182 self ._max_help_position = min (max_help_position ,
@@ -281,10 +282,13 @@ def add_argument(self, action):
281282 if action .help is not SUPPRESS :
282283
283284 # find all invocations
284- get_invocation = lambda x : self ._decolor (self ._format_action_invocation (x ))
285- invocation_lengths = [len (get_invocation (action )) + self ._current_indent ]
285+ def get_invocation (x ): return self ._decolor (
286+ self ._format_action_invocation (x ))
287+ invocation_lengths = [
288+ len (get_invocation (action )) + self ._current_indent ]
286289 for subaction in self ._iter_indented_subactions (action ):
287- invocation_lengths .append (len (get_invocation (subaction )) + self ._current_indent )
290+ invocation_lengths .append (
291+ len (get_invocation (subaction )) + self ._current_indent )
288292
289293 # update the maximum item length
290294 action_length = max (invocation_lengths )
@@ -432,7 +436,8 @@ def _get_actions_usage_parts(self, actions, groups):
432436 continue
433437
434438 try :
435- start = min (actions .index (item ) for item in group ._group_actions )
439+ start = min (actions .index (item )
440+ for item in group ._group_actions )
436441 except ValueError :
437442 continue
438443 else :
@@ -499,7 +504,8 @@ def _get_actions_usage_parts(self, actions, groups):
499504 inserted_separators_indices = set ()
500505 for start , end in sorted (inserts , reverse = True ):
501506 group = inserts [start , end ]
502- group_parts = [item for item in parts [start :end ] if item is not None ]
507+ group_parts = [
508+ item for item in parts [start :end ] if item is not None ]
503509 group_size = len (group_parts )
504510 if group .required :
505511 open , close = "()" if group_size > 1 else ("" , "" )
@@ -753,7 +759,6 @@ def _get_help_string(self, action):
753759 return help
754760
755761
756-
757762class MetavarTypeHelpFormatter (HelpFormatter ):
758763 """Help message formatter which uses the argument 'type' as the default
759764 metavar value (instead of the argument 'dest')
@@ -952,7 +957,6 @@ def __init__(self,
952957 help = help ,
953958 deprecated = deprecated )
954959
955-
956960 def __call__ (self , parser , namespace , values , option_string = None ):
957961 if option_string in self .option_strings :
958962 setattr (namespace , self .dest , not option_string .startswith ('--no-' ))
@@ -1314,7 +1318,8 @@ def __call__(self, parser, namespace, values, option_string=None):
13141318 # In case this subparser defines new defaults, we parse them
13151319 # in a new namespace object and then update the original
13161320 # namespace for the relevant parts.
1317- subnamespace , arg_strings = subparser .parse_known_args (arg_strings , None )
1321+ subnamespace , arg_strings = subparser .parse_known_args (
1322+ arg_strings , None )
13181323 for key , value in vars (subnamespace ).items ():
13191324 setattr (namespace , key , value )
13201325
@@ -1323,6 +1328,7 @@ def __call__(self, parser, namespace, values, option_string=None):
13231328 setattr (namespace , _UNRECOGNIZED_ARGS_ATTR , [])
13241329 getattr (namespace , _UNRECOGNIZED_ARGS_ATTR ).extend (arg_strings )
13251330
1331+
13261332class _ExtendAction (_AppendAction ):
13271333 def __call__ (self , parser , namespace , values , option_string = None ):
13281334 items = getattr (namespace , self .dest , None )
@@ -1334,6 +1340,7 @@ def __call__(self, parser, namespace, values, option_string=None):
13341340# Type classes
13351341# ==============
13361342
1343+
13371344class FileType (object ):
13381345 """Deprecated factory for creating file object types
13391346
@@ -1395,6 +1402,7 @@ def __repr__(self):
13951402# Optional and Positional Parsing
13961403# ===========================
13971404
1405+
13981406class Namespace (_AttributeHolder ):
13991407 """Simple object for storing attributes.
14001408
@@ -1497,7 +1505,6 @@ def get_default(self, dest):
14971505 return action .default
14981506 return self ._defaults .get (dest , None )
14991507
1500-
15011508 # =======================
15021509 # Adding argument actions
15031510 # =======================
@@ -1540,7 +1547,8 @@ def add_argument(self, *args, **kwargs):
15401547 # raise an error if action for positional argument does not
15411548 # consume arguments
15421549 if not action .option_strings and action .nargs == 0 :
1543- raise ValueError (f'action { action_name !r} is not valid for positional arguments' )
1550+ raise ValueError (
1551+ f'action { action_name !r} is not valid for positional arguments' )
15441552
15451553 # raise an error if the action type is not callable
15461554 type_func = self ._registry_get ('type' , action .type , action .type )
@@ -1557,7 +1565,8 @@ def add_argument(self, *args, **kwargs):
15571565 try :
15581566 formatter ._format_args (action , None )
15591567 except TypeError :
1560- raise ValueError ("length of metavar tuple does not match nargs" )
1568+ raise ValueError (
1569+ "length of metavar tuple does not match nargs" )
15611570 self ._check_help (action )
15621571 return self ._add_action (action )
15631572
@@ -1793,6 +1802,7 @@ def _remove_action(self, action):
17931802 def add_argument_group (self , * args , ** kwargs ):
17941803 raise ValueError ('argument groups cannot be nested' )
17951804
1805+
17961806class _MutuallyExclusiveGroup (_ArgumentGroup ):
17971807
17981808 def __init__ (self , container , required = False ):
@@ -1815,6 +1825,7 @@ def _remove_action(self, action):
18151825 def add_mutually_exclusive_group (self , ** kwargs ):
18161826 raise ValueError ('mutually exclusive groups cannot be nested' )
18171827
1828+
18181829def _prog_name (prog = None ):
18191830 if prog is not None :
18201831 return prog
@@ -2039,11 +2050,13 @@ def _parse_known_args2(self, args, namespace, intermixed):
20392050 # parse the arguments and exit if there are any errors
20402051 if self .exit_on_error :
20412052 try :
2042- namespace , args = self ._parse_known_args (args , namespace , intermixed )
2053+ namespace , args = self ._parse_known_args (
2054+ args , namespace , intermixed )
20432055 except ArgumentError as err :
20442056 self .error (str (err ))
20452057 else :
2046- namespace , args = self ._parse_known_args (args , namespace , intermixed )
2058+ namespace , args = self ._parse_known_args (
2059+ args , namespace , intermixed )
20472060
20482061 if hasattr (namespace , _UNRECOGNIZED_ARGS_ATTR ):
20492062 args .extend (getattr (namespace , _UNRECOGNIZED_ARGS_ATTR ))
@@ -2125,7 +2138,7 @@ def consume_optional(start_index):
21252138 # if multiple actions match, the option string was ambiguous
21262139 if len (option_tuples ) > 1 :
21272140 options = ', ' .join ([option_string
2128- for action , option_string , sep , explicit_arg in option_tuples ])
2141+ for action , option_string , sep , explicit_arg in option_tuples ])
21292142 args = {'option' : arg_strings [start_index ], 'matches' : options }
21302143 msg = _ ('ambiguous option: %(option)s could match %(matches)s' )
21312144 raise ArgumentError (None , msg % args )
@@ -2286,7 +2299,8 @@ def consume_positionals(start_index):
22862299 if start_index not in option_string_indices :
22872300 strings = arg_strings [start_index :next_option_string_index ]
22882301 extras .extend (strings )
2289- extras_pattern .extend (arg_strings_pattern [start_index :next_option_string_index ])
2302+ extras_pattern .extend (
2303+ arg_strings_pattern [start_index :next_option_string_index ])
22902304 start_index = next_option_string_index
22912305
22922306 # consume the next optional and any arguments for it
@@ -2304,7 +2318,8 @@ def consume_positionals(start_index):
23042318 extras_pattern = '' .join (extras_pattern )
23052319 assert len (extras_pattern ) == len (extras )
23062320 # consume all positionals
2307- arg_strings = [s for s , c in zip (extras , extras_pattern ) if c != 'O' ]
2321+ arg_strings = [s for s , c in zip (
2322+ extras , extras_pattern ) if c != 'O' ]
23082323 arg_strings_pattern = extras_pattern .replace ('O' , '' )
23092324 stop_index = consume_positionals (0 )
23102325 # leave unknown optionals and non-consumed positionals in extras
@@ -2331,13 +2346,13 @@ def consume_positionals(start_index):
23312346 if (action .default is not None and
23322347 isinstance (action .default , str ) and
23332348 hasattr (namespace , action .dest ) and
2334- action .default is getattr (namespace , action .dest )):
2349+ action .default is getattr (namespace , action .dest )):
23352350 setattr (namespace , action .dest ,
23362351 self ._get_value (action , action .default ))
23372352
23382353 if required_actions :
23392354 raise ArgumentError (None , _ ('the following arguments are required: %s' ) %
2340- ', ' .join (required_actions ))
2355+ ', ' .join (required_actions ))
23412356
23422357 # make sure all required groups had one option present
23432358 for group in self ._mutually_exclusive_groups :
@@ -2420,7 +2435,7 @@ def _match_arguments_partial(self, actions, arg_strings_pattern):
24202435 if match is not None :
24212436 result = [len (string ) for string in match .groups ()]
24222437 if (match .end () < len (arg_strings_pattern )
2423- and arg_strings_pattern [match .end ()] == 'O' ):
2438+ and arg_strings_pattern [match .end ()] == 'O' ):
24242439 while result and not result [- 1 ]:
24252440 del result [- 1 ]
24262441 return result
@@ -2511,7 +2526,8 @@ def _get_option_tuples(self, option_string):
25112526
25122527 # shouldn't ever get here
25132528 else :
2514- raise ArgumentError (None , _ ('unexpected option string: %s' ) % option_string )
2529+ raise ArgumentError (
2530+ None , _ ('unexpected option string: %s' ) % option_string )
25152531
25162532 # return the collected option tuples
25172533 return result
@@ -2586,7 +2602,7 @@ def parse_known_intermixed_args(self, args=None, namespace=None):
25862602 if action .nargs in [PARSER , REMAINDER ]]
25872603 if a :
25882604 raise TypeError ('parse_intermixed_args: positional arg'
2589- ' with nargs=%s' % a [0 ].nargs )
2605+ ' with nargs=%s' % a [0 ].nargs )
25902606
25912607 return self ._parse_known_args2 (args , namespace , intermixed = True )
25922608
@@ -2682,7 +2698,8 @@ def _check_value(self, action, value):
26822698 if self .suggest_on_error and isinstance (value , str ):
26832699 if all (isinstance (choice , str ) for choice in action .choices ):
26842700 import difflib
2685- suggestions = difflib .get_close_matches (value , action .choices , 1 )
2701+ suggestions = difflib .get_close_matches (
2702+ value , action .choices , 1 )
26862703 if suggestions :
26872704 args ['closest' ] = suggestions [0 ]
26882705 msg = _ ('invalid choice: %(value)r, maybe you meant %(closest)r? '
@@ -2774,4 +2791,5 @@ def error(self, message):
27742791
27752792 def _warning (self , message ):
27762793 args = {'prog' : self .prog , 'message' : message }
2777- self ._print_message (_ ('%(prog)s: warning: %(message)s\n ' ) % args , _sys .stderr )
2794+ self ._print_message (
2795+ _ ('%(prog)s: warning: %(message)s\n ' ) % args , _sys .stderr )
0 commit comments