summaryrefslogtreecommitdiff
path: root/cmd2/argparse_custom.py
diff options
context:
space:
mode:
authorxNinjaKittyx <xNinjaKittyx@users.noreply.github.com>2020-12-15 17:21:33 -0800
committerxNinjaKittyx <xNinjaKittyx@users.noreply.github.com>2020-12-15 18:20:13 -0800
commit9aa54a5b27468d61337528cb1e1b5b9b11a80978 (patch)
tree567693115cc101efb9254a96d96d80e9f9ccd557 /cmd2/argparse_custom.py
parent03c65c60b39e369958b056c5c844d36d515c8a63 (diff)
downloadcmd2-git-ci_improvements.tar.gz
Adds pre-commit config to run various lintersci_improvements
This ads black, isort, pyupgrade, and flake8 to pre-commit-config.yaml There are also some small changes to travis.yml and tasks.py to reduce some repeated configurations that should be consolidated into setup.cfg. Most other changes are automated by the linter scripts.
Diffstat (limited to 'cmd2/argparse_custom.py')
-rw-r--r--cmd2/argparse_custom.py93
1 files changed, 56 insertions, 37 deletions
diff --git a/cmd2/argparse_custom.py b/cmd2/argparse_custom.py
index d773f851..bd9e4cfb 100644
--- a/cmd2/argparse_custom.py
+++ b/cmd2/argparse_custom.py
@@ -219,6 +219,7 @@ more details.
import argparse
import re
import sys
+
# noinspection PyUnresolvedReferences,PyProtectedMember
from argparse import ONE_OR_MORE, ZERO_OR_MORE, ArgumentError, _
from typing import Any, Callable, Optional, Tuple, Type, Union
@@ -270,6 +271,7 @@ class CompletionItem(str):
See header of this file for more information
"""
+
def __new__(cls, value: object, *args, **kwargs) -> str:
return super().__new__(cls, value)
@@ -295,6 +297,7 @@ class ChoicesCallable:
Enables using a callable as the choices provider for an argparse argument.
While argparse has the built-in choices attribute, it is limited to an iterable.
"""
+
def __init__(self, is_method: bool, is_completer: bool, to_call: Callable):
"""
Initializer
@@ -317,12 +320,16 @@ def _set_choices_callable(action: argparse.Action, choices_callable: ChoicesCall
"""
# Verify consistent use of parameters
if action.choices is not None:
- err_msg = ("None of the following parameters can be used alongside a choices parameter:\n"
- "choices_function, choices_method, completer_function, completer_method")
+ err_msg = (
+ "None of the following parameters can be used alongside a choices parameter:\n"
+ "choices_function, choices_method, completer_function, completer_method"
+ )
raise (TypeError(err_msg))
elif action.nargs == 0:
- err_msg = ("None of the following parameters can be used on an action that takes no arguments:\n"
- "choices_function, choices_method, completer_function, completer_method")
+ err_msg = (
+ "None of the following parameters can be used on an action that takes no arguments:\n"
+ "choices_function, choices_method, completer_function, completer_method"
+ )
raise (TypeError(err_msg))
setattr(action, ATTR_CHOICES_CALLABLE, choices_callable)
@@ -357,15 +364,18 @@ def set_completer_method(action: argparse.Action, completer_method: Callable) ->
orig_actions_container_add_argument = argparse._ActionsContainer.add_argument
-def _add_argument_wrapper(self, *args,
- nargs: Union[int, str, Tuple[int], Tuple[int, int], None] = None,
- choices_function: Optional[Callable] = None,
- choices_method: Optional[Callable] = None,
- completer_function: Optional[Callable] = None,
- completer_method: Optional[Callable] = None,
- suppress_tab_hint: bool = False,
- descriptive_header: Optional[str] = None,
- **kwargs) -> argparse.Action:
+def _add_argument_wrapper(
+ self,
+ *args,
+ nargs: Union[int, str, Tuple[int], Tuple[int, int], None] = None,
+ choices_function: Optional[Callable] = None,
+ choices_method: Optional[Callable] = None,
+ completer_function: Optional[Callable] = None,
+ completer_method: Optional[Callable] = None,
+ suppress_tab_hint: bool = False,
+ descriptive_header: Optional[str] = None,
+ **kwargs
+) -> argparse.Action:
"""
Wrapper around _ActionsContainer.add_argument() which supports more settings used by cmd2
@@ -405,8 +415,10 @@ def _add_argument_wrapper(self, *args,
num_params_set = len(choices_callables) - choices_callables.count(None)
if num_params_set > 1:
- err_msg = ("Only one of the following parameters may be used at a time:\n"
- "choices_function, choices_method, completer_function, completer_method")
+ err_msg = (
+ "Only one of the following parameters may be used at a time:\n"
+ "choices_function, choices_method, completer_function, completer_method"
+ )
raise (ValueError(err_msg))
# Pre-process special ranged nargs
@@ -421,8 +433,11 @@ def _add_argument_wrapper(self, *args,
nargs = (nargs[0], constants.INFINITY)
# Validate nargs tuple
- if len(nargs) != 2 or not isinstance(nargs[0], int) or \
- not (isinstance(nargs[1], int) or nargs[1] == constants.INFINITY):
+ if (
+ len(nargs) != 2
+ or not isinstance(nargs[0], int)
+ or not (isinstance(nargs[1], int) or nargs[1] == constants.INFINITY)
+ ):
raise ValueError('Ranged values for nargs must be a tuple of 1 or 2 integers')
if nargs[0] >= nargs[1]:
raise ValueError('Invalid nargs range. The first value must be less than the second')
@@ -669,7 +684,7 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
if line:
lines.append(indent + ' '.join(line))
if prefix is not None:
- lines[0] = lines[0][len(indent):]
+ lines[0] = lines[0][len(indent) :]
return lines
# if prog is short, follow it with optionals or positionals
@@ -707,12 +722,12 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
usage = '\n'.join(lines)
# prefix with 'Usage:'
- return '%s%s\n\n' % (prefix, usage)
+ return '{}{}\n\n'.format(prefix, usage)
def _format_action_invocation(self, action) -> str:
if not action.option_strings:
default = self._get_default_metavar_for_positional(action)
- metavar, = self._metavar_formatter(action, default)(1)
+ (metavar,) = self._metavar_formatter(action, default)(1)
return metavar
else:
@@ -756,7 +771,8 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
if isinstance(metavar, tuple):
return metavar
else:
- return (metavar, ) * tuple_size
+ return (metavar,) * tuple_size
+
return format
# noinspection PyProtectedMember
@@ -792,19 +808,21 @@ class Cmd2HelpFormatter(argparse.RawTextHelpFormatter):
class Cmd2ArgumentParser(argparse.ArgumentParser):
"""Custom ArgumentParser class that improves error and help output"""
- def __init__(self,
- prog=None,
- usage=None,
- description=None,
- epilog=None,
- parents=None,
- formatter_class=Cmd2HelpFormatter,
- prefix_chars='-',
- fromfile_prefix_chars=None,
- argument_default=None,
- conflict_handler='error',
- add_help=True,
- allow_abbrev=True) -> None:
+ def __init__(
+ self,
+ prog=None,
+ usage=None,
+ description=None,
+ epilog=None,
+ parents=None,
+ formatter_class=Cmd2HelpFormatter,
+ prefix_chars='-',
+ fromfile_prefix_chars=None,
+ argument_default=None,
+ conflict_handler='error',
+ add_help=True,
+ allow_abbrev=True,
+ ) -> None:
super(Cmd2ArgumentParser, self).__init__(
prog=prog,
usage=usage,
@@ -817,7 +835,8 @@ class Cmd2ArgumentParser(argparse.ArgumentParser):
argument_default=argument_default,
conflict_handler=conflict_handler,
add_help=add_help,
- allow_abbrev=allow_abbrev)
+ allow_abbrev=allow_abbrev,
+ )
def add_subparsers(self, **kwargs):
"""
@@ -853,8 +872,7 @@ class Cmd2ArgumentParser(argparse.ArgumentParser):
formatter = self._get_formatter()
# usage
- formatter.add_usage(self.usage, self._actions,
- self._mutually_exclusive_groups)
+ formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
# description
formatter.add_text(self.description)
@@ -912,6 +930,7 @@ class Cmd2AttributeWrapper:
This makes it easy to know which attributes in a Namespace are
arguments from a parser and which were added by cmd2.
"""
+
def __init__(self, attribute: Any):
self.__attribute = attribute