Skip to content

Commit 374a885

Browse files
committed
Enable ruff TC type checking ruleset and accept automated refactorings
1 parent 263aa3f commit 374a885

File tree

8 files changed

+42
-42
lines changed

8 files changed

+42
-42
lines changed

cmd2/ansi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def style_aware_wcswidth(text: str) -> int:
106106
then this function returns -1. Replace tabs with spaces before calling this.
107107
"""
108108
# Strip ANSI style sequences since they cause wcswidth to return -1
109-
return cast(int, wcswidth(strip_style(text)))
109+
return cast('int', wcswidth(strip_style(text)))
110110

111111

112112
def widest_line(text: str) -> int:

cmd2/argparse_custom.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ def _action_get_choices_callable(self: argparse.Action) -> Optional[ChoicesCalla
455455
:param self: argparse Action being queried
456456
:return: A ChoicesCallable instance or None if attribute does not exist
457457
"""
458-
return cast(Optional[ChoicesCallable], getattr(self, ATTR_CHOICES_CALLABLE, None))
458+
return cast("Optional[ChoicesCallable]", getattr(self, ATTR_CHOICES_CALLABLE, None))
459459

460460

461461
setattr(argparse.Action, 'get_choices_callable', _action_get_choices_callable)
@@ -545,7 +545,7 @@ def _action_get_descriptive_header(self: argparse.Action) -> Optional[str]:
545545
:param self: argparse Action being queried
546546
:return: The value of descriptive_header or None if attribute does not exist
547547
"""
548-
return cast(Optional[str], getattr(self, ATTR_DESCRIPTIVE_HEADER, None))
548+
return cast("Optional[str]", getattr(self, ATTR_DESCRIPTIVE_HEADER, None))
549549

550550

551551
setattr(argparse.Action, 'get_descriptive_header', _action_get_descriptive_header)
@@ -582,7 +582,7 @@ def _action_get_nargs_range(self: argparse.Action) -> Optional[Tuple[int, Union[
582582
:param self: argparse Action being queried
583583
:return: The value of nargs_range or None if attribute does not exist
584584
"""
585-
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))
586586

587587

588588
setattr(argparse.Action, 'get_nargs_range', _action_get_nargs_range)
@@ -619,7 +619,7 @@ def _action_get_suppress_tab_hint(self: argparse.Action) -> bool:
619619
:param self: argparse Action being queried
620620
:return: The value of suppress_tab_hint or False if attribute does not exist
621621
"""
622-
return cast(bool, getattr(self, ATTR_SUPPRESS_TAB_HINT, False))
622+
return cast("bool", getattr(self, ATTR_SUPPRESS_TAB_HINT, False))
623623

624624

625625
setattr(argparse.Action, 'get_suppress_tab_hint', _action_get_suppress_tab_hint)
@@ -929,7 +929,7 @@ def _ArgumentParser_get_ap_completer_type(self: argparse.ArgumentParser) -> Opti
929929
:param self: ArgumentParser being queried
930930
:return: An ArgparseCompleter-based class or None if attribute does not exist
931931
"""
932-
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))
933933

934934

935935
setattr(argparse.ArgumentParser, 'get_ap_completer_type', _ArgumentParser_get_ap_completer_type)

cmd2/clipboard.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def get_paste_buffer() -> str:
1313
1414
:return: contents of the clipboard
1515
"""
16-
pb_str = typing.cast(str, pyperclip.paste())
16+
pb_str = typing.cast("str", pyperclip.paste())
1717
return pb_str
1818

1919

cmd2/cmd2.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@
183183
)
184184

185185
rl_basic_quote_characters = ctypes.c_char_p.in_dll(readline_lib, "rl_basic_quote_characters")
186-
orig_rl_basic_quotes = cast(bytes, ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value)
186+
orig_rl_basic_quotes = cast("bytes", ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value)
187187

188188

189189
class _SavedReadlineSettings:
@@ -715,7 +715,7 @@ def register_command_set(self, cmdset: CommandSet) -> None:
715715

716716
cmdset.on_register(self)
717717
methods = cast(
718-
List[Tuple[str, Callable[..., Any]]],
718+
"List[Tuple[str, Callable[..., Any]]]",
719719
inspect.getmembers(
720720
cmdset,
721721
predicate=lambda meth: isinstance(meth, Callable) # type: ignore[arg-type]
@@ -978,7 +978,7 @@ def find_subcommand(action: argparse.ArgumentParser, subcmd_names: List[str]) ->
978978

979979
target_parser = find_subcommand(command_parser, subcommand_names)
980980

981-
subcmd_parser = cast(argparse.ArgumentParser, self._build_parser(cmdset, subcmd_parser_builder))
981+
subcmd_parser = cast("argparse.ArgumentParser", self._build_parser(cmdset, subcmd_parser_builder))
982982
from .decorators import (
983983
_set_parser_prog,
984984
)
@@ -1161,7 +1161,7 @@ def allow_style_type(value: str) -> ansi.AllowStyle:
11611161
'Allow ANSI text style sequences in output (valid values: '
11621162
f'{ansi.AllowStyle.ALWAYS}, {ansi.AllowStyle.NEVER}, {ansi.AllowStyle.TERMINAL})',
11631163
self,
1164-
choices_provider=cast(ChoicesProviderFunc, get_allow_style_choices),
1164+
choices_provider=cast("ChoicesProviderFunc", get_allow_style_choices),
11651165
)
11661166
)
11671167

@@ -1953,7 +1953,7 @@ def _display_matches_gnu_readline(
19531953

19541954
# rl_display_match_list() expects matches to be in argv format where
19551955
# substitution is the first element, followed by the matches, and then a NULL.
1956-
strings_array = cast(List[Optional[bytes]], (ctypes.c_char_p * (1 + len(encoded_matches) + 1))())
1956+
strings_array = cast("List[Optional[bytes]]", (ctypes.c_char_p * (1 + len(encoded_matches) + 1))())
19571957

19581958
# Copy in the encoded strings and add a NULL to the end
19591959
strings_array[0] = encoded_substitution
@@ -2877,7 +2877,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
28772877

28782878
# Initialize the redirection saved state
28792879
redir_saved_state = utils.RedirectionSavedState(
2880-
cast(TextIO, self.stdout), sys.stdout, self._cur_pipe_proc_reader, self._redirecting
2880+
cast("TextIO", self.stdout), sys.stdout, self._cur_pipe_proc_reader, self._redirecting
28812881
)
28822882

28832883
# The ProcReader for this command
@@ -2893,7 +2893,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
28932893

28942894
# Open each side of the pipe
28952895
subproc_stdin = io.open(read_fd, 'r')
2896-
new_stdout: TextIO = cast(TextIO, io.open(write_fd, 'w'))
2896+
new_stdout: TextIO = cast("TextIO", io.open(write_fd, 'w'))
28972897

28982898
# Create pipe process in a separate group to isolate our signals from it. If a Ctrl-C event occurs,
28992899
# our sigint handler will forward it only to the most recent pipe process. This makes sure pipe
@@ -2934,7 +2934,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
29342934
new_stdout.close()
29352935
raise RedirectionError(f'Pipe process exited with code {proc.returncode} before command could run')
29362936
redir_saved_state.redirecting = True # type: ignore[unreachable]
2937-
cmd_pipe_proc_reader = utils.ProcReader(proc, cast(TextIO, self.stdout), sys.stderr)
2937+
cmd_pipe_proc_reader = utils.ProcReader(proc, cast("TextIO", self.stdout), sys.stderr)
29382938
sys.stdout = self.stdout = new_stdout
29392939

29402940
elif statement.output:
@@ -2944,7 +2944,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
29442944
mode = 'a' if statement.output == constants.REDIRECTION_APPEND else 'w'
29452945
try:
29462946
# Use line buffering
2947-
new_stdout = cast(TextIO, open(utils.strip_quotes(statement.output_to), mode=mode, buffering=1))
2947+
new_stdout = cast("TextIO", open(utils.strip_quotes(statement.output_to), mode=mode, buffering=1))
29482948
except OSError as ex:
29492949
raise RedirectionError(f'Failed to redirect because: {ex}')
29502950

@@ -2965,7 +2965,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
29652965
# no point opening up the temporary file
29662966
current_paste_buffer = get_paste_buffer()
29672967
# create a temporary file to store output
2968-
new_stdout = cast(TextIO, tempfile.TemporaryFile(mode="w+"))
2968+
new_stdout = cast("TextIO", tempfile.TemporaryFile(mode="w+"))
29692969
redir_saved_state.redirecting = True
29702970
sys.stdout = self.stdout = new_stdout
29712971

@@ -2998,8 +2998,8 @@ def _restore_output(self, statement: Statement, saved_redir_state: utils.Redirec
29982998
pass
29992999

30003000
# Restore the stdout values
3001-
self.stdout = cast(TextIO, saved_redir_state.saved_self_stdout)
3002-
sys.stdout = cast(TextIO, saved_redir_state.saved_sys_stdout)
3001+
self.stdout = cast("TextIO", saved_redir_state.saved_self_stdout)
3002+
sys.stdout = cast("TextIO", saved_redir_state.saved_sys_stdout)
30033003

30043004
# Check if we need to wait for the process being piped to
30053005
if self._cur_pipe_proc_reader is not None:
@@ -3025,7 +3025,7 @@ def cmd_func(self, command: str) -> Optional[CommandFunc]:
30253025
"""
30263026
func_name = constants.COMMAND_FUNC_PREFIX + command
30273027
func = getattr(self, func_name, None)
3028-
return cast(CommandFunc, func) if callable(func) else None
3028+
return cast("CommandFunc", func) if callable(func) else None
30293029

30303030
def onecmd(self, statement: Union[Statement, str], *, add_to_history: bool = True) -> bool:
30313031
"""This executes the actual do_* method for a command.
@@ -3285,7 +3285,7 @@ def _set_up_cmd2_readline(self) -> _SavedReadlineSettings:
32853285
# We don't want this behavior since cmd2 only adds a closing quote when self.allow_closing_quote is True.
32863286
# To fix this behavior, set readline's rl_basic_quote_characters to NULL. We don't need to worry about setting
32873287
# rl_completion_suppress_quote since we never declared rl_completer_quote_characters.
3288-
readline_settings.basic_quotes = cast(bytes, ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value)
3288+
readline_settings.basic_quotes = cast("bytes", ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value)
32893289
rl_basic_quote_characters.value = None
32903290

32913291
readline_settings.completer = readline.get_completer()
@@ -3950,7 +3950,7 @@ def _build_command_info(self) -> Tuple[Dict[str, List[str]], List[str], List[str
39503950
cmds_undoc: List[str] = []
39513951
cmds_cats: Dict[str, List[str]] = {}
39523952
for command in visible_commands:
3953-
func = cast(CommandFunc, self.cmd_func(command))
3953+
func = cast("CommandFunc", self.cmd_func(command))
39543954
has_help_func = False
39553955
has_parser = func in self._command_parsers
39563956

@@ -4020,7 +4020,7 @@ def _print_topics(self, header: str, cmds: List[str], verbose: bool) -> None:
40204020
stdout_orig = self.stdout
40214021
try:
40224022
# redirect our internal stdout
4023-
self.stdout = cast(TextIO, result)
4023+
self.stdout = cast("TextIO", result)
40244024
help_func()
40254025
finally:
40264026
# restore internal stdout
@@ -4087,7 +4087,7 @@ def select(self, opts: Union[str, List[str], List[Tuple[Any, Optional[str]]]], p
40874087
the text advertised to the user"""
40884088
local_opts: Union[List[str], List[Tuple[Any, Optional[str]]]]
40894089
if isinstance(opts, str):
4090-
local_opts = cast(List[Tuple[Any, Optional[str]]], list(zip(opts.split(), opts.split())))
4090+
local_opts = cast("List[Tuple[Any, Optional[str]]]", list(zip(opts.split(), opts.split())))
40914091
else:
40924092
local_opts = opts
40934093
fulloptions: List[Tuple[Any, Optional[str]]] = []
@@ -4287,7 +4287,7 @@ def do_shell(self, args: argparse.Namespace) -> None:
42874287
**kwargs,
42884288
)
42894289

4290-
proc_reader = utils.ProcReader(proc, cast(TextIO, self.stdout), sys.stderr) # type: ignore[arg-type]
4290+
proc_reader = utils.ProcReader(proc, cast("TextIO", self.stdout), sys.stderr) # type: ignore[arg-type]
42914291
proc_reader.wait()
42924292

42934293
# Save the return code of the application for use in a pyscript
@@ -4346,7 +4346,7 @@ def _set_up_py_shell_env(self, interp: InteractiveConsole) -> _SavedCmd2Env:
43464346
# rlcompleter relies on the default settings of the Python readline module
43474347
if rl_type == RlType.GNU:
43484348
cmd2_env.readline_settings.basic_quotes = cast(
4349-
bytes, ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
4349+
"bytes", ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
43504350
)
43514351
rl_basic_quote_characters.value = orig_rl_basic_quotes
43524352

@@ -4995,8 +4995,8 @@ def _generate_transcript(
49954995
transcript += command
49964996

49974997
# Use a StdSim object to capture output
4998-
stdsim = utils.StdSim(cast(TextIO, self.stdout))
4999-
self.stdout = cast(TextIO, stdsim)
4998+
stdsim = utils.StdSim(cast("TextIO", self.stdout))
4999+
self.stdout = cast("TextIO", stdsim)
50005000

50015001
# then run the command and let the output go into our buffer
50025002
try:
@@ -5021,7 +5021,7 @@ def _generate_transcript(
50215021
with self.sigint_protection:
50225022
# Restore altered attributes to their original state
50235023
self.echo = saved_echo
5024-
self.stdout = cast(TextIO, saved_stdout)
5024+
self.stdout = cast("TextIO", saved_stdout)
50255025

50265026
# Check if all commands ran
50275027
if commands_run < len(history):
@@ -5235,7 +5235,7 @@ class TestMyAppCase(Cmd2TestCase):
52355235
setattr(self.__class__, 'testfiles', transcripts_expanded)
52365236
sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()
52375237
testcase = TestMyAppCase()
5238-
stream = cast(TextIO, utils.StdSim(sys.stderr))
5238+
stream = cast("TextIO", utils.StdSim(sys.stderr))
52395239
runner = unittest.TextTestRunner(stream=stream)
52405240
start_time = time.time()
52415241
test_results = runner.run(testcase)
@@ -5624,7 +5624,7 @@ def register_postloop_hook(self, func: Callable[[], None]) -> None:
56245624
@classmethod
56255625
def _validate_postparsing_callable(cls, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None:
56265626
"""Check parameter and return types for postparsing hooks"""
5627-
cls._validate_callable_param_count(cast(Callable[..., Any], func), 1)
5627+
cls._validate_callable_param_count(cast("Callable[..., Any]", func), 1)
56285628
signature = inspect.signature(func)
56295629
_, param = list(signature.parameters.items())[0]
56305630
if param.annotation != plugin.PostparsingData:
@@ -5646,7 +5646,7 @@ def _validate_prepostcmd_hook(
56465646
"""Check parameter and return types for pre and post command hooks."""
56475647
signature = inspect.signature(func)
56485648
# validate that the callable has the right number of parameters
5649-
cls._validate_callable_param_count(cast(Callable[..., Any], func), 1)
5649+
cls._validate_callable_param_count(cast("Callable[..., Any]", func), 1)
56505650
# validate the parameter has the right annotation
56515651
paramname = list(signature.parameters.keys())[0]
56525652
param = signature.parameters[paramname]

cmd2/py_bridge.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def __call__(self, command: str, *, echo: Optional[bool] = None) -> CommandResul
117117
echo = self.cmd_echo
118118

119119
# This will be used to capture _cmd2_app.stdout and sys.stdout
120-
copy_cmd_stdout = StdSim(cast(Union[TextIO, StdSim], self._cmd2_app.stdout), echo=echo)
120+
copy_cmd_stdout = StdSim(cast('Union[TextIO, StdSim]', self._cmd2_app.stdout), echo=echo)
121121

122122
# Pause the storing of stdout until onecmd_plus_hooks enables it
123123
copy_cmd_stdout.pause_storage = True
@@ -129,17 +129,17 @@ def __call__(self, command: str, *, echo: Optional[bool] = None) -> CommandResul
129129

130130
stop = False
131131
try:
132-
self._cmd2_app.stdout = cast(TextIO, copy_cmd_stdout)
133-
with redirect_stdout(cast(IO[str], copy_cmd_stdout)):
134-
with redirect_stderr(cast(IO[str], copy_stderr)):
132+
self._cmd2_app.stdout = cast('TextIO', copy_cmd_stdout)
133+
with redirect_stdout(cast('IO[str]', copy_cmd_stdout)):
134+
with redirect_stderr(cast('IO[str]', copy_stderr)):
135135
stop = self._cmd2_app.onecmd_plus_hooks(
136136
command,
137137
add_to_history=self._add_to_history,
138138
py_bridge_call=True,
139139
)
140140
finally:
141141
with self._cmd2_app.sigint_protection:
142-
self._cmd2_app.stdout = cast(IO[str], copy_cmd_stdout.inner_stream)
142+
self._cmd2_app.stdout = cast('IO[str]', copy_cmd_stdout.inner_stream)
143143
self.stop = stop or self.stop
144144

145145
# Save the result

cmd2/transcript.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def setUp(self) -> None:
5151

5252
# Trap stdout
5353
self._orig_stdout = self.cmdapp.stdout
54-
self.cmdapp.stdout = cast(TextIO, utils.StdSim(cast(TextIO, self.cmdapp.stdout)))
54+
self.cmdapp.stdout = cast('TextIO', utils.StdSim(cast('TextIO', self.cmdapp.stdout)))
5555

5656
def tearDown(self) -> None:
5757
if self.cmdapp:
@@ -66,7 +66,7 @@ def runTest(self) -> None: # was testall
6666

6767
def _fetchTranscripts(self) -> None:
6868
self.transcripts = {}
69-
testfiles = cast(List[str], getattr(self.cmdapp, 'testfiles', []))
69+
testfiles = cast('List[str]', getattr(self.cmdapp, 'testfiles', []))
7070
for fname in testfiles:
7171
tfile = open(fname)
7272
self.transcripts[fname] = iter(tfile.readlines())

cmd2/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def get_bool_choices(_) -> List[str]: # type: ignore[no-untyped-def]
164164
return ['true', 'false']
165165

166166
val_type = to_bool
167-
choices_provider = cast(ChoicesProviderFunc, get_bool_choices)
167+
choices_provider = cast('ChoicesProviderFunc', get_bool_choices)
168168

169169
self.name = name
170170
self.val_type = val_type
@@ -1194,7 +1194,7 @@ def get_defining_class(meth: Callable[..., Any]) -> Optional[Type[Any]]:
11941194
cls = getattr(inspect.getmodule(meth), meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0])
11951195
if isinstance(cls, type):
11961196
return cls
1197-
return cast(type, getattr(meth, '__objclass__', None)) # handle special descriptor objects
1197+
return cast('type', getattr(meth, '__objclass__', None)) # handle special descriptor objects
11981198

11991199

12001200
class CompletionMode(Enum):

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ select = [
212212
# "SLOT", # flake8-slots (warn about subclasses that should define __slots__)
213213
"T10", # flake8-debugger (check for pdb traces left in Python code)
214214
# "T20", # flake8-print (warn about use of `print` or `pprint` - force use of loggers)
215-
# "TC", # flake8-type-checking (type checking warnings)
215+
"TC", # flake8-type-checking (type checking warnings)
216216
# "TD", # flake8-todos (force all TODOs to include an author and issue link)
217217
"TID", # flake8-tidy-imports (extra import rules to check)
218218
# "TRY", # tryceratops (warnings related to exceptions and try/except)

0 commit comments

Comments
 (0)