Skip to content

Commit 5490ed6

Browse files
committed
Finish reverting ruff rule TC006 changes and added that to the ignore list
This rule forced every use of typing inside a cast to be quoted. In reality, it is only forward reference types which needed this.
1 parent 7cad725 commit 5490ed6

File tree

4 files changed

+33
-32
lines changed

4 files changed

+33
-32
lines changed

cmd2/argparse_custom.py

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

452452

453453
setattr(argparse.Action, 'get_choices_callable', _action_get_choices_callable)
@@ -537,7 +537,7 @@ def _action_get_descriptive_header(self: argparse.Action) -> Optional[str]:
537537
:param self: argparse Action being queried
538538
:return: The value of descriptive_header or None if attribute does not exist
539539
"""
540-
return cast("Optional[str]", getattr(self, ATTR_DESCRIPTIVE_HEADER, None))
540+
return cast(Optional[str], getattr(self, ATTR_DESCRIPTIVE_HEADER, None))
541541

542542

543543
setattr(argparse.Action, 'get_descriptive_header', _action_get_descriptive_header)
@@ -574,7 +574,7 @@ def _action_get_nargs_range(self: argparse.Action) -> Optional[tuple[int, Union[
574574
:param self: argparse Action being queried
575575
:return: The value of nargs_range or None if attribute does not exist
576576
"""
577-
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))
578578

579579

580580
setattr(argparse.Action, 'get_nargs_range', _action_get_nargs_range)
@@ -611,7 +611,7 @@ def _action_get_suppress_tab_hint(self: argparse.Action) -> bool:
611611
:param self: argparse Action being queried
612612
:return: The value of suppress_tab_hint or False if attribute does not exist
613613
"""
614-
return cast("bool", getattr(self, ATTR_SUPPRESS_TAB_HINT, False))
614+
return cast(bool, getattr(self, ATTR_SUPPRESS_TAB_HINT, False))
615615

616616

617617
setattr(argparse.Action, 'get_suppress_tab_hint', _action_get_suppress_tab_hint)
@@ -921,7 +921,7 @@ def _ArgumentParser_get_ap_completer_type(self: argparse.ArgumentParser) -> Opti
921921
:param self: ArgumentParser being queried
922922
:return: An ArgparseCompleter-based class or None if attribute does not exist
923923
"""
924-
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))
925925

926926

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

cmd2/cmd2.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@
175175
)
176176

177177
rl_basic_quote_characters = ctypes.c_char_p.in_dll(readline_lib, "rl_basic_quote_characters")
178-
orig_rl_basic_quotes = cast("bytes", ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value)
178+
orig_rl_basic_quotes = cast(bytes, ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value)
179179

180180

181181
class _SavedReadlineSettings:
@@ -707,7 +707,7 @@ def register_command_set(self, cmdset: CommandSet) -> None:
707707

708708
cmdset.on_register(self)
709709
methods = cast(
710-
"list[tuple[str, Callable[..., Any]]]",
710+
list[tuple[str, Callable[..., Any]]],
711711
inspect.getmembers(
712712
cmdset,
713713
predicate=lambda meth: isinstance(meth, Callable) # type: ignore[arg-type]
@@ -970,7 +970,7 @@ def find_subcommand(action: argparse.ArgumentParser, subcmd_names: list[str]) ->
970970

971971
target_parser = find_subcommand(command_parser, subcommand_names)
972972

973-
subcmd_parser = cast("argparse.ArgumentParser", self._build_parser(cmdset, subcmd_parser_builder))
973+
subcmd_parser = cast(argparse.ArgumentParser, self._build_parser(cmdset, subcmd_parser_builder))
974974
from .decorators import (
975975
_set_parser_prog,
976976
)
@@ -1153,7 +1153,7 @@ def allow_style_type(value: str) -> ansi.AllowStyle:
11531153
'Allow ANSI text style sequences in output (valid values: '
11541154
f'{ansi.AllowStyle.ALWAYS}, {ansi.AllowStyle.NEVER}, {ansi.AllowStyle.TERMINAL})',
11551155
self,
1156-
choices_provider=cast("ChoicesProviderFunc", get_allow_style_choices),
1156+
choices_provider=cast(ChoicesProviderFunc, get_allow_style_choices),
11571157
)
11581158
)
11591159

@@ -1945,7 +1945,7 @@ def _display_matches_gnu_readline(
19451945

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

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

28692869
# Initialize the redirection saved state
28702870
redir_saved_state = utils.RedirectionSavedState(
2871-
cast("TextIO", self.stdout), sys.stdout, self._cur_pipe_proc_reader, self._redirecting
2871+
cast(TextIO, self.stdout), sys.stdout, self._cur_pipe_proc_reader, self._redirecting
28722872
)
28732873

28742874
# The ProcReader for this command
@@ -2884,7 +2884,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
28842884

28852885
# Open each side of the pipe
28862886
subproc_stdin = open(read_fd)
2887-
new_stdout: TextIO = cast("TextIO", open(write_fd, 'w'))
2887+
new_stdout: TextIO = cast(TextIO, open(write_fd, 'w'))
28882888

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

29312931
elif statement.output:
@@ -2935,7 +2935,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
29352935
mode = 'a' if statement.output == constants.REDIRECTION_APPEND else 'w'
29362936
try:
29372937
# Use line buffering
2938-
new_stdout = cast("TextIO", open(utils.strip_quotes(statement.output_to), mode=mode, buffering=1))
2938+
new_stdout = cast(TextIO, open(utils.strip_quotes(statement.output_to), mode=mode, buffering=1))
29392939
except OSError as ex:
29402940
raise RedirectionError(f'Failed to redirect because: {ex}')
29412941

@@ -2956,7 +2956,7 @@ def _redirect_output(self, statement: Statement) -> utils.RedirectionSavedState:
29562956
# no point opening up the temporary file
29572957
current_paste_buffer = get_paste_buffer()
29582958
# create a temporary file to store output
2959-
new_stdout = cast("TextIO", tempfile.TemporaryFile(mode="w+"))
2959+
new_stdout = cast(TextIO, tempfile.TemporaryFile(mode="w+"))
29602960
redir_saved_state.redirecting = True
29612961
sys.stdout = self.stdout = new_stdout
29622962

@@ -2989,8 +2989,8 @@ def _restore_output(self, statement: Statement, saved_redir_state: utils.Redirec
29892989
pass
29902990

29912991
# Restore the stdout values
2992-
self.stdout = cast("TextIO", saved_redir_state.saved_self_stdout)
2993-
sys.stdout = cast("TextIO", saved_redir_state.saved_sys_stdout)
2992+
self.stdout = cast(TextIO, saved_redir_state.saved_self_stdout)
2993+
sys.stdout = cast(TextIO, saved_redir_state.saved_sys_stdout)
29942994

29952995
# Check if we need to wait for the process being piped to
29962996
if self._cur_pipe_proc_reader is not None:
@@ -3016,7 +3016,7 @@ def cmd_func(self, command: str) -> Optional[CommandFunc]:
30163016
"""
30173017
func_name = constants.COMMAND_FUNC_PREFIX + command
30183018
func = getattr(self, func_name, None)
3019-
return cast("CommandFunc", func) if callable(func) else None
3019+
return cast(CommandFunc, func) if callable(func) else None
30203020

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

32823282
readline_settings.completer = readline.get_completer()
@@ -3941,7 +3941,7 @@ def _build_command_info(self) -> tuple[dict[str, list[str]], list[str], list[str
39413941
cmds_undoc: list[str] = []
39423942
cmds_cats: dict[str, list[str]] = {}
39433943
for command in visible_commands:
3944-
func = cast("CommandFunc", self.cmd_func(command))
3944+
func = cast(CommandFunc, self.cmd_func(command))
39453945
has_help_func = False
39463946
has_parser = func in self._command_parsers
39473947

@@ -4011,7 +4011,7 @@ def _print_topics(self, header: str, cmds: list[str], verbose: bool) -> None:
40114011
stdout_orig = self.stdout
40124012
try:
40134013
# redirect our internal stdout
4014-
self.stdout = cast("TextIO", result)
4014+
self.stdout = cast(TextIO, result)
40154015
help_func()
40164016
finally:
40174017
# restore internal stdout
@@ -4078,7 +4078,7 @@ def select(self, opts: Union[str, list[str], list[tuple[Any, Optional[str]]]], p
40784078
the text advertised to the user"""
40794079
local_opts: Union[list[str], list[tuple[Any, Optional[str]]]]
40804080
if isinstance(opts, str):
4081-
local_opts = cast("list[tuple[Any, Optional[str]]]", list(zip(opts.split(), opts.split())))
4081+
local_opts = cast(list[tuple[Any, Optional[str]]], list(zip(opts.split(), opts.split())))
40824082
else:
40834083
local_opts = opts
40844084
fulloptions: list[tuple[Any, Optional[str]]] = []
@@ -4278,7 +4278,7 @@ def do_shell(self, args: argparse.Namespace) -> None:
42784278
**kwargs,
42794279
)
42804280

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

42844284
# Save the return code of the application for use in a pyscript
@@ -4337,7 +4337,7 @@ def _set_up_py_shell_env(self, interp: InteractiveConsole) -> _SavedCmd2Env:
43374337
# rlcompleter relies on the default settings of the Python readline module
43384338
if rl_type == RlType.GNU:
43394339
cmd2_env.readline_settings.basic_quotes = cast(
4340-
"bytes", ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
4340+
bytes, ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
43414341
)
43424342
rl_basic_quote_characters.value = orig_rl_basic_quotes
43434343

@@ -4986,8 +4986,8 @@ def _generate_transcript(
49864986
transcript += command
49874987

49884988
# Use a StdSim object to capture output
4989-
stdsim = utils.StdSim(cast("TextIO", self.stdout))
4990-
self.stdout = cast("TextIO", stdsim)
4989+
stdsim = utils.StdSim(cast(TextIO, self.stdout))
4990+
self.stdout = cast(TextIO, stdsim)
49914991

49924992
# then run the command and let the output go into our buffer
49934993
try:
@@ -5012,7 +5012,7 @@ def _generate_transcript(
50125012
with self.sigint_protection:
50135013
# Restore altered attributes to their original state
50145014
self.echo = saved_echo
5015-
self.stdout = cast("TextIO", saved_stdout)
5015+
self.stdout = cast(TextIO, saved_stdout)
50165016

50175017
# Check if all commands ran
50185018
if commands_run < len(history):
@@ -5226,7 +5226,7 @@ class TestMyAppCase(Cmd2TestCase):
52265226
setattr(self.__class__, 'testfiles', transcripts_expanded)
52275227
sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()
52285228
testcase = TestMyAppCase()
5229-
stream = cast("TextIO", utils.StdSim(sys.stderr))
5229+
stream = cast(TextIO, utils.StdSim(sys.stderr))
52305230
runner = unittest.TextTestRunner(stream=stream)
52315231
start_time = time.time()
52325232
test_results = runner.run(testcase)
@@ -5615,7 +5615,7 @@ def register_postloop_hook(self, func: Callable[[], None]) -> None:
56155615
@classmethod
56165616
def _validate_postparsing_callable(cls, func: Callable[[plugin.PostparsingData], plugin.PostparsingData]) -> None:
56175617
"""Check parameter and return types for postparsing hooks"""
5618-
cls._validate_callable_param_count(cast("Callable[..., Any]", func), 1)
5618+
cls._validate_callable_param_count(cast(Callable[..., Any], func), 1)
56195619
signature = inspect.signature(func)
56205620
_, param = list(signature.parameters.items())[0]
56215621
if param.annotation != plugin.PostparsingData:
@@ -5637,7 +5637,7 @@ def _validate_prepostcmd_hook(
56375637
"""Check parameter and return types for pre and post command hooks."""
56385638
signature = inspect.signature(func)
56395639
# validate that the callable has the right number of parameters
5640-
cls._validate_callable_param_count(cast("Callable[..., Any]", func), 1)
5640+
cls._validate_callable_param_count(cast(Callable[..., Any], func), 1)
56415641
# validate the parameter has the right annotation
56425642
paramname = list(signature.parameters.keys())[0]
56435643
param = signature.parameters[paramname]

cmd2/transcript.py

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

4949
# Trap stdout
5050
self._orig_stdout = self.cmdapp.stdout
51-
self.cmdapp.stdout = cast('TextIO', utils.StdSim(cast('TextIO', self.cmdapp.stdout)))
51+
self.cmdapp.stdout = cast(TextIO, utils.StdSim(cast(TextIO, self.cmdapp.stdout)))
5252

5353
def tearDown(self) -> None:
5454
if self.cmdapp:
@@ -63,7 +63,7 @@ def runTest(self) -> None: # was testall
6363

6464
def _fetchTranscripts(self) -> None:
6565
self.transcripts = {}
66-
testfiles = cast('list[str]', getattr(self.cmdapp, 'testfiles', []))
66+
testfiles = cast(list[str], getattr(self.cmdapp, 'testfiles', []))
6767
for fname in testfiles:
6868
tfile = open(fname)
6969
self.transcripts[fname] = iter(tfile.readlines())

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ select = [
222222
]
223223
ignore = [
224224
# `uv run ruff rule E501` for a description of that rule
225+
"TC006", # Add quotes to type expression in typing.cast() (not needed except for forward references)
225226
"UP007", # Use X | Y for type annotations (requires Python 3.10+)
226227
"UP017", # Use datetime.UTC alias (requires Python 3.11+)
227228
]

0 commit comments

Comments
 (0)