Skip to content

Commit 57ffd7b

Browse files
authored
Use type hinting generics in standard collections instead of importing from typing (#1377)
1 parent 410849c commit 57ffd7b

32 files changed

+255
-338
lines changed

cmd2/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,6 @@
1111
# package is not installed
1212
pass
1313

14-
from typing import List
15-
1614
from . import plugin
1715
from .ansi import (
1816
Bg,
@@ -64,7 +62,7 @@
6462
categorize,
6563
)
6664

67-
__all__: List[str] = [
65+
__all__: list[str] = [
6866
'COMMAND_NAME',
6967
'DEFAULT_SHORTCUTS',
7068
# ANSI Exports

cmd2/ansi.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
from typing import (
1313
IO,
1414
Any,
15-
List,
1615
Optional,
1716
cast,
1817
)
@@ -992,11 +991,11 @@ def style(
992991
:raises: TypeError if bg isn't None or a subclass of BgColor
993992
:return: the stylized string
994993
"""
995-
# List of strings that add style
996-
additions: List[AnsiSequence] = []
994+
# list of strings that add style
995+
additions: list[AnsiSequence] = []
997996

998-
# List of strings that remove style
999-
removals: List[AnsiSequence] = []
997+
# list of strings that remove style
998+
removals: list[AnsiSequence] = []
1000999

10011000
# Process the style settings
10021001
if fg is not None:

cmd2/argparse_completer.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@
1414
)
1515
from typing import (
1616
TYPE_CHECKING,
17-
Dict,
18-
List,
1917
Optional,
2018
Type,
2119
Union,
@@ -172,7 +170,7 @@ class ArgparseCompleter:
172170
"""Automatic command line tab completion based on argparse parameters"""
173171

174172
def __init__(
175-
self, parser: argparse.ArgumentParser, cmd2_app: 'Cmd', *, parent_tokens: Optional[Dict[str, List[str]]] = None
173+
self, parser: argparse.ArgumentParser, cmd2_app: 'Cmd', *, parent_tokens: Optional[dict[str, list[str]]] = None
176174
) -> None:
177175
"""
178176
Create an ArgparseCompleter
@@ -213,8 +211,8 @@ def __init__(
213211
self._subcommand_action = action
214212

215213
def complete(
216-
self, text: str, line: str, begidx: int, endidx: int, tokens: List[str], *, cmd_set: Optional[CommandSet] = None
217-
) -> List[str]:
214+
self, text: str, line: str, begidx: int, endidx: int, tokens: list[str], *, cmd_set: Optional[CommandSet] = None
215+
) -> list[str]:
218216
"""
219217
Complete text using argparse metadata
220218
@@ -245,13 +243,13 @@ def complete(
245243
flag_arg_state: Optional[_ArgumentState] = None
246244

247245
# Non-reusable flags that we've parsed
248-
matched_flags: List[str] = []
246+
matched_flags: list[str] = []
249247

250248
# Keeps track of arguments we've seen and any tokens they consumed
251-
consumed_arg_values: Dict[str, List[str]] = dict() # dict(arg_name -> List[tokens])
249+
consumed_arg_values: dict[str, list[str]] = dict() # dict(arg_name -> l[tokens])
252250

253251
# Completed mutually exclusive groups
254-
completed_mutex_groups: Dict[argparse._MutuallyExclusiveGroup, argparse.Action] = dict()
252+
completed_mutex_groups: dict[argparse._MutuallyExclusiveGroup, argparse.Action] = dict()
255253

256254
def consume_argument(arg_state: _ArgumentState) -> None:
257255
"""Consuming token as an argument"""
@@ -507,7 +505,7 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:
507505

508506
return completion_results
509507

510-
def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, matched_flags: List[str]) -> List[str]:
508+
def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, matched_flags: list[str]) -> list[str]:
511509
"""Tab completion routine for a parsers unused flags"""
512510

513511
# Build a list of flags that can be tab completed
@@ -524,7 +522,7 @@ def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, matche
524522
matches = self._cmd2_app.basic_complete(text, line, begidx, endidx, match_against)
525523

526524
# Build a dictionary linking actions with their matched flag names
527-
matched_actions: Dict[argparse.Action, List[str]] = dict()
525+
matched_actions: dict[argparse.Action, list[str]] = dict()
528526
for flag in matches:
529527
action = self._flag_to_action[flag]
530528
matched_actions.setdefault(action, [])
@@ -541,14 +539,14 @@ def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, matche
541539

542540
return matches
543541

544-
def _format_completions(self, arg_state: _ArgumentState, completions: Union[List[str], List[CompletionItem]]) -> List[str]:
542+
def _format_completions(self, arg_state: _ArgumentState, completions: Union[list[str], list[CompletionItem]]) -> list[str]:
545543
"""Format CompletionItems into hint table"""
546544

547545
# Nothing to do if we don't have at least 2 completions which are all CompletionItems
548546
if len(completions) < 2 or not all(isinstance(c, CompletionItem) for c in completions):
549-
return cast(List[str], completions)
547+
return cast(list[str], completions)
550548

551-
completion_items = cast(List[CompletionItem], completions)
549+
completion_items = cast(list[CompletionItem], completions)
552550

553551
# Check if the data being completed have a numerical type
554552
all_nums = all(isinstance(c.orig_value, numbers.Number) for c in completion_items)
@@ -616,17 +614,17 @@ def _format_completions(self, arg_state: _ArgumentState, completions: Union[List
616614
self._cmd2_app.formatted_completions = hint_table.generate_table(table_data, row_spacing=0)
617615

618616
# Return sorted list of completions
619-
return cast(List[str], completions)
617+
return cast(list[str], completions)
620618

621-
def complete_subcommand_help(self, text: str, line: str, begidx: int, endidx: int, tokens: List[str]) -> List[str]:
619+
def complete_subcommand_help(self, text: str, line: str, begidx: int, endidx: int, tokens: list[str]) -> list[str]:
622620
"""
623621
Supports cmd2's help command in the completion of subcommand names
624622
:param text: the string prefix we are attempting to match (all matches must begin with it)
625623
:param line: the current input line with leading whitespace removed
626624
:param begidx: the beginning index of the prefix text
627625
:param endidx: the ending index of the prefix text
628626
:param tokens: arguments passed to command/subcommand
629-
:return: List of subcommand completions
627+
:return: list of subcommand completions
630628
"""
631629
# If our parser has subcommands, we must examine the tokens and check if they are subcommands
632630
# If so, we will let the subcommand's parser handle the rest of the tokens via another ArgparseCompleter.
@@ -645,7 +643,7 @@ def complete_subcommand_help(self, text: str, line: str, begidx: int, endidx: in
645643
break
646644
return []
647645

648-
def format_help(self, tokens: List[str]) -> str:
646+
def format_help(self, tokens: list[str]) -> str:
649647
"""
650648
Supports cmd2's help command in the retrieval of help text
651649
:param tokens: arguments passed to help command
@@ -672,17 +670,17 @@ def _complete_arg(
672670
begidx: int,
673671
endidx: int,
674672
arg_state: _ArgumentState,
675-
consumed_arg_values: Dict[str, List[str]],
673+
consumed_arg_values: dict[str, list[str]],
676674
*,
677675
cmd_set: Optional[CommandSet] = None,
678-
) -> List[str]:
676+
) -> list[str]:
679677
"""
680678
Tab completion routine for an argparse argument
681679
:return: list of completions
682680
:raises: CompletionError if the completer or choices function this calls raises one
683681
"""
684682
# Check if the arg provides choices to the user
685-
arg_choices: Union[List[str], ChoicesCallable]
683+
arg_choices: Union[list[str], ChoicesCallable]
686684
if arg_state.action.choices is not None:
687685
arg_choices = list(arg_state.action.choices)
688686
if not arg_choices:
@@ -739,7 +737,7 @@ def _complete_arg(
739737
# Otherwise use basic_complete on the choices
740738
else:
741739
# Check if the choices come from a function
742-
completion_items: List[str] = []
740+
completion_items: list[str] = []
743741
if isinstance(arg_choices, ChoicesCallable):
744742
if not arg_choices.is_completer:
745743
choices_func = arg_choices.choices_provider

cmd2/argparse_custom.py

Lines changed: 22 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -250,15 +250,11 @@ def my_completer(self, text, line, begidx, endidx, arg_tokens)
250250
TYPE_CHECKING,
251251
Any,
252252
Callable,
253-
Dict,
254253
Iterable,
255-
List,
256254
NoReturn,
257255
Optional,
258256
Protocol,
259257
Sequence,
260-
Set,
261-
Tuple,
262258
Type,
263259
Union,
264260
cast,
@@ -350,7 +346,7 @@ class ChoicesProviderFuncBase(Protocol):
350346
Function that returns a list of choices in support of tab completion
351347
"""
352348

353-
def __call__(self) -> List[str]: ... # pragma: no cover
349+
def __call__(self) -> list[str]: ... # pragma: no cover
354350

355351

356352
@runtime_checkable
@@ -359,7 +355,7 @@ class ChoicesProviderFuncWithTokens(Protocol):
359355
Function that returns a list of choices in support of tab completion and accepts a dictionary of prior arguments.
360356
"""
361357

362-
def __call__(self, *, arg_tokens: Dict[str, List[str]] = {}) -> List[str]: ... # pragma: no cover
358+
def __call__(self, *, arg_tokens: dict[str, list[str]] = {}) -> list[str]: ... # pragma: no cover
363359

364360

365361
ChoicesProviderFunc = Union[ChoicesProviderFuncBase, ChoicesProviderFuncWithTokens]
@@ -377,7 +373,7 @@ def __call__(
377373
line: str,
378374
begidx: int,
379375
endidx: int,
380-
) -> List[str]: ... # pragma: no cover
376+
) -> list[str]: ... # pragma: no cover
381377

382378

383379
@runtime_checkable
@@ -394,8 +390,8 @@ def __call__(
394390
begidx: int,
395391
endidx: int,
396392
*,
397-
arg_tokens: Dict[str, List[str]] = {},
398-
) -> List[str]: ... # pragma: no cover
393+
arg_tokens: dict[str, list[str]] = {},
394+
) -> list[str]: ... # pragma: no cover
399395

400396

401397
CompleterFunc = Union[CompleterFuncBase, CompleterFuncWithTokens]
@@ -598,7 +594,7 @@ def _action_set_descriptive_header(self: argparse.Action, descriptive_header: Op
598594
############################################################################################################
599595
# Patch argparse.Action with accessors for nargs_range attribute
600596
############################################################################################################
601-
def _action_get_nargs_range(self: argparse.Action) -> Optional[Tuple[int, Union[int, float]]]:
597+
def _action_get_nargs_range(self: argparse.Action) -> Optional[tuple[int, Union[int, float]]]:
602598
"""
603599
Get the nargs_range attribute of an argparse Action.
604600
@@ -609,13 +605,13 @@ def _action_get_nargs_range(self: argparse.Action) -> Optional[Tuple[int, Union[
609605
:param self: argparse Action being queried
610606
:return: The value of nargs_range or None if attribute does not exist
611607
"""
612-
return cast(Optional[Tuple[int, Union[int, float]]], getattr(self, ATTR_NARGS_RANGE, None))
608+
return cast(Optional[tuple[int, Union[int, float]]], getattr(self, ATTR_NARGS_RANGE, None))
613609

614610

615611
setattr(argparse.Action, 'get_nargs_range', _action_get_nargs_range)
616612

617613

618-
def _action_set_nargs_range(self: argparse.Action, nargs_range: Optional[Tuple[int, Union[int, float]]]) -> None:
614+
def _action_set_nargs_range(self: argparse.Action, nargs_range: Optional[tuple[int, Union[int, float]]]) -> None:
619615
"""
620616
Set the nargs_range attribute of an argparse Action.
621617
@@ -673,7 +669,7 @@ def _action_set_suppress_tab_hint(self: argparse.Action, suppress_tab_hint: bool
673669
# Allow developers to add custom action attributes
674670
############################################################################################################
675671

676-
CUSTOM_ACTION_ATTRIBS: Set[str] = set()
672+
CUSTOM_ACTION_ATTRIBS: set[str] = set()
677673
_CUSTOM_ATTRIB_PFX = '_attr_'
678674

679675

@@ -746,7 +742,7 @@ def _action_set_custom_parameter(self: argparse.Action, value: Any) -> None:
746742
def _add_argument_wrapper(
747743
self: argparse._ActionsContainer,
748744
*args: Any,
749-
nargs: Union[int, str, Tuple[int], Tuple[int, int], Tuple[int, float], None] = None,
745+
nargs: Union[int, str, tuple[int], tuple[int, int], tuple[int, float], None] = None,
750746
choices_provider: Optional[ChoicesProviderFunc] = None,
751747
completer: Optional[CompleterFunc] = None,
752748
suppress_tab_hint: bool = False,
@@ -797,7 +793,7 @@ def _add_argument_wrapper(
797793
nargs_range = None
798794

799795
if nargs is not None:
800-
nargs_adjusted: Union[int, str, Tuple[int], Tuple[int, int], Tuple[int, float], None]
796+
nargs_adjusted: Union[int, str, tuple[int], tuple[int, int], tuple[int, float], None]
801797
# Check if nargs was given as a range
802798
if isinstance(nargs, tuple):
803799
# Handle 1-item tuple by setting max to INFINITY
@@ -847,7 +843,7 @@ def _add_argument_wrapper(
847843
kwargs['nargs'] = nargs_adjusted
848844

849845
# Extract registered custom keyword arguments
850-
custom_attribs: Dict[str, Any] = {}
846+
custom_attribs: dict[str, Any] = {}
851847
for keyword, value in kwargs.items():
852848
if keyword in CUSTOM_ACTION_ATTRIBS:
853849
custom_attribs[keyword] = value
@@ -1124,9 +1120,9 @@ def _format_usage(
11241120
# End cmd2 customization
11251121

11261122
# helper for wrapping lines
1127-
def get_lines(parts: List[str], indent: str, prefix: Optional[str] = None) -> List[str]:
1128-
lines: List[str] = []
1129-
line: List[str] = []
1123+
def get_lines(parts: list[str], indent: str, prefix: Optional[str] = None) -> list[str]:
1124+
lines: list[str] = []
1125+
line: list[str] = []
11301126
if prefix is not None:
11311127
line_len = len(prefix) - 1
11321128
else:
@@ -1188,7 +1184,7 @@ def _format_action_invocation(self, action: argparse.Action) -> str:
11881184
return metavar
11891185

11901186
else:
1191-
parts: List[str] = []
1187+
parts: list[str] = []
11921188

11931189
# if the Optional doesn't take a value, format is:
11941190
# -s, --long
@@ -1209,8 +1205,8 @@ def _format_action_invocation(self, action: argparse.Action) -> str:
12091205
def _determine_metavar(
12101206
self,
12111207
action: argparse.Action,
1212-
default_metavar: Union[str, Tuple[str, ...]],
1213-
) -> Union[str, Tuple[str, ...]]:
1208+
default_metavar: Union[str, tuple[str, ...]],
1209+
) -> Union[str, tuple[str, ...]]:
12141210
"""Custom method to determine what to use as the metavar value of an action"""
12151211
if action.metavar is not None:
12161212
result = action.metavar
@@ -1226,19 +1222,19 @@ def _determine_metavar(
12261222
def _metavar_formatter(
12271223
self,
12281224
action: argparse.Action,
1229-
default_metavar: Union[str, Tuple[str, ...]],
1230-
) -> Callable[[int], Tuple[str, ...]]:
1225+
default_metavar: Union[str, tuple[str, ...]],
1226+
) -> Callable[[int], tuple[str, ...]]:
12311227
metavar = self._determine_metavar(action, default_metavar)
12321228

1233-
def format(tuple_size: int) -> Tuple[str, ...]:
1229+
def format(tuple_size: int) -> tuple[str, ...]:
12341230
if isinstance(metavar, tuple):
12351231
return metavar
12361232
else:
12371233
return (metavar,) * tuple_size
12381234

12391235
return format
12401236

1241-
def _format_args(self, action: argparse.Action, default_metavar: Union[str, Tuple[str, ...]]) -> str:
1237+
def _format_args(self, action: argparse.Action, default_metavar: Union[str, tuple[str, ...]]) -> str:
12421238
"""Customized to handle ranged nargs and make other output less verbose"""
12431239
metavar = self._determine_metavar(action, default_metavar)
12441240
metavar_formatter = self._metavar_formatter(action, default_metavar)

0 commit comments

Comments
 (0)