Skip to content

Commit c9fa34d

Browse files
committed
Do a bunch of automated refactoring using ruff UP ruleset to do things like replace .format() with f-strings
1 parent d503ef9 commit c9fa34d

16 files changed

+272
-275
lines changed

cmd2/argparse_completer.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
from typing import (
1313
TYPE_CHECKING,
1414
Optional,
15-
Type,
1615
Union,
1716
cast,
1817
)
@@ -143,11 +142,9 @@ def __init__(self, flag_arg_state: _ArgumentState) -> None:
143142
CompletionError which occurs when the user has not finished the current flag
144143
:param flag_arg_state: information about the unfinished flag action
145144
"""
146-
error = "Error: argument {}: {} ({} entered)".format(
147-
argparse._get_action_name(flag_arg_state.action),
148-
generate_range_error(cast(int, flag_arg_state.min), cast(Union[int, float], flag_arg_state.max)),
149-
flag_arg_state.count,
150-
)
145+
arg = f'{argparse._get_action_name(flag_arg_state.action)}'
146+
err = f'{generate_range_error(cast(int, flag_arg_state.min), cast(Union[int, float], flag_arg_state.max))}'
147+
error = f"Error: argument {arg}: {err} ({flag_arg_state.count} entered)"
151148
super().__init__(error)
152149

153150

@@ -272,9 +269,9 @@ def update_mutex_groups(arg_action: argparse.Action) -> None:
272269
if arg_action == completer_action:
273270
return
274271

275-
error = "Error: argument {}: not allowed with argument {}".format(
276-
argparse._get_action_name(arg_action), argparse._get_action_name(completer_action)
277-
)
272+
arg_str = f'{argparse._get_action_name(arg_action)}'
273+
completer_str = f'{argparse._get_action_name(completer_action)}'
274+
error = f"Error: argument {arg_str}: not allowed with argument {completer_str}"
278275
raise CompletionError(error)
279276

280277
# Mark that this action completed the group
@@ -766,10 +763,10 @@ def _complete_arg(
766763

767764

768765
# The default ArgparseCompleter class for a cmd2 app
769-
DEFAULT_AP_COMPLETER: Type[ArgparseCompleter] = ArgparseCompleter
766+
DEFAULT_AP_COMPLETER: type[ArgparseCompleter] = ArgparseCompleter
770767

771768

772-
def set_default_ap_completer_type(completer_type: Type[ArgparseCompleter]) -> None:
769+
def set_default_ap_completer_type(completer_type: type[ArgparseCompleter]) -> None:
773770
"""
774771
Set the default ArgparseCompleter class for a cmd2 app.
775772

examples/modular_commands/commandset_complex.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def do_banana(self, statement: cmd2.Statement):
2121

2222
@cmd2.with_argparser(cranberry_parser, with_unknown_args=True)
2323
def do_cranberry(self, ns: argparse.Namespace, unknown: list[str]):
24-
self._cmd.poutput('Cranberry {}!!'.format(ns.arg1))
24+
self._cmd.poutput(f'Cranberry {ns.arg1}!!')
2525
if unknown and len(unknown):
2626
self._cmd.poutput('Unknown: ' + ', '.join(['{}'] * len(unknown)).format(*unknown))
2727
self._cmd.last_result = {'arg1': ns.arg1, 'unknown': unknown}
@@ -33,7 +33,7 @@ def help_cranberry(self):
3333
@cmd2.with_category('Also Alone')
3434
def do_durian(self, args: list[str]):
3535
"""Durian Command"""
36-
self._cmd.poutput('{} Arguments: '.format(len(args)))
36+
self._cmd.poutput(f'{len(args)} Arguments: ')
3737
self._cmd.poutput(', '.join(['{}'] * len(args)).format(*args))
3838

3939
def complete_durian(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
@@ -45,4 +45,4 @@ def complete_durian(self, text: str, line: str, begidx: int, endidx: int) -> lis
4545
@cmd2.with_category('Alone')
4646
@cmd2.with_argparser(elderberry_parser)
4747
def do_elderberry(self, ns: argparse.Namespace):
48-
self._cmd.poutput('Elderberry {}!!'.format(ns.arg1))
48+
self._cmd.poutput(f'Elderberry {ns.arg1}!!')

examples/scripts/conditional.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,36 +14,36 @@
1414

1515
if len(sys.argv) > 1:
1616
directory = sys.argv[1]
17-
print('Using specified directory: {!r}'.format(directory))
17+
print(f'Using specified directory: {directory!r}')
1818
else:
1919
directory = 'foobar'
20-
print('Using default directory: {!r}'.format(directory))
20+
print(f'Using default directory: {directory!r}')
2121

2222
# Keep track of where we stared
2323
original_dir = os.getcwd()
2424

2525
# Try to change to the specified directory
26-
result = app('cd {}'.format(directory))
26+
result = app(f'cd {directory}')
2727

2828
# Conditionally do something based on the results of the last command
2929
if result:
3030
print(f"STDOUT: {result.stdout}\n")
3131
print(f"STDERR: {result.stderr}\n")
3232

33-
print('\nContents of directory {!r}:'.format(directory))
33+
print(f'\nContents of directory {directory!r}:')
3434
result = app('dir -l')
3535

3636
print(f"STDOUT: {result.stdout}\n")
3737
print(f"STDERR: {result.stderr}\n")
3838

39-
print('{}\n'.format(result.data))
39+
print(f'{result.data}\n')
4040

4141
# Change back to where we were
42-
print('Changing back to original directory: {!r}'.format(original_dir))
43-
app('cd {}'.format(original_dir))
42+
print(f'Changing back to original directory: {original_dir!r}')
43+
app(f'cd {original_dir}')
4444
else:
4545
# cd command failed, print a warning
46-
print('Failed to change directory to {!r}'.format(directory))
46+
print(f'Failed to change directory to {directory!r}')
4747

4848
print(f"STDOUT: {result.stdout}\n")
4949
print(f"STDERR: {result.stderr}\n")

examples/scripts/save_help_text.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ def add_help_to_file(item: str, outfile: TextIO, is_command: bool) -> None:
4343
else:
4444
label = "TOPIC"
4545

46-
header = '{}\n{}: {}\n{}\n'.format(ASTERISKS, label, item, ASTERISKS)
46+
header = f'{ASTERISKS}\n{label}: {item}\n{ASTERISKS}\n'
4747
outfile.write(header)
4848

49-
result = app('help {}'.format(item))
49+
result = app(f'help {item}')
5050
outfile.write(result.stdout)
5151

5252

@@ -60,19 +60,19 @@ def main() -> None:
6060

6161
# Make sure the user passed in an output file
6262
if len(sys.argv) != 2:
63-
print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
63+
print(f"Usage: {os.path.basename(sys.argv[0])} <output_file>")
6464
return
6565

6666
# Open the output file
6767
outfile_path = os.path.expanduser(sys.argv[1])
6868
try:
6969
outfile = open(outfile_path, 'w')
7070
except OSError as e:
71-
print("Error opening {} because: {}".format(outfile_path, e))
71+
print(f"Error opening {outfile_path} because: {e}")
7272
return
7373

7474
# Write the help summary
75-
header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
75+
header = f'{ASTERISKS}\nSUMMARY\n{ASTERISKS}\n'
7676
outfile.write(header)
7777

7878
result = app('help -v')
@@ -91,11 +91,11 @@ def main() -> None:
9191
if is_command:
9292
# Add any subcommands
9393
for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
94-
full_cmd = '{} {}'.format(item, subcmd)
94+
full_cmd = f'{item} {subcmd}'
9595
add_help_to_file(full_cmd, outfile, is_command)
9696

9797
outfile.close()
98-
print("Output written to {}".format(outfile_path))
98+
print(f"Output written to {outfile_path}")
9999

100100

101101
# Run main function

tasks.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def rmrf(items, verbose=True):
3030

3131
for item in items:
3232
if verbose:
33-
print("Removing {}".format(item))
33+
print(f"Removing {item}")
3434
shutil.rmtree(item, ignore_errors=True)
3535
# rmtree doesn't remove bare files
3636
try:
@@ -270,8 +270,8 @@ def tag(context, name, message=''):
270270
"""Add a Git tag and push it to origin"""
271271
# If a tag was provided on the command-line, then add a Git tag and push it to origin
272272
if name:
273-
context.run('git tag -a {} -m {!r}'.format(name, message))
274-
context.run('git push origin {}'.format(name))
273+
context.run(f'git tag -a {name} -m {message!r}')
274+
context.run(f'git push origin {name}')
275275

276276

277277
namespace.add_task(tag)
@@ -288,10 +288,10 @@ def validatetag(context):
288288
ver_regex = re.compile(r'(\d+)\.(\d+)\.(\d+)')
289289
match = ver_regex.fullmatch(git_tag)
290290
if match is None:
291-
print('Tag {!r} does not appear to be a valid version number'.format(git_tag))
291+
print(f'Tag {git_tag!r} does not appear to be a valid version number')
292292
sys.exit(-1)
293293
else:
294-
print('Tag {!r} appears to be a valid version number'.format(git_tag))
294+
print(f'Tag {git_tag!r} appears to be a valid version number')
295295

296296

297297
namespace.add_task(validatetag)

tests/pyscript/environment.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@
55
app.cmd_echo = True
66

77
if __name__ != '__main__':
8-
print("Error: __name__ is: {}".format(__name__))
8+
print(f"Error: __name__ is: {__name__}")
99
quit()
1010

1111
if __file__ != sys.argv[0]:
12-
print("Error: __file__ is: {}".format(__file__))
12+
print(f"Error: __file__ is: {__file__}")
1313
quit()
1414

1515
our_dir = os.path.dirname(os.path.abspath(__file__))
1616
if our_dir != sys.path[0]:
17-
print("Error: our_dir is: {}".format(our_dir))
17+
print(f"Error: our_dir is: {our_dir}")
1818
quit()
1919

2020
print("PASSED")

tests/test_argparse.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def do_tag(self, args):
7070

7171
@cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=namespace_provider)
7272
def do_test_argparse_ns(self, args):
73-
self.stdout.write('{}'.format(args.custom_stuff))
73+
self.stdout.write(f'{args.custom_stuff}')
7474

7575
@cmd2.with_argument_list
7676
def do_arglist(self, arglist, *, keyword_arg: Optional[str] = None):
@@ -84,7 +84,7 @@ def do_arglist(self, arglist, *, keyword_arg: Optional[str] = None):
8484

8585
@cmd2.with_argument_list(preserve_quotes=True)
8686
def do_preservelist(self, arglist):
87-
self.stdout.write('{}'.format(arglist))
87+
self.stdout.write(f'{arglist}')
8888

8989
@classmethod
9090
def _speak_parser_builder(cls) -> cmd2.Cmd2ArgumentParser:
@@ -120,7 +120,7 @@ def do_test_argparse_with_list_quotes(self, args, extra):
120120

121121
@cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=namespace_provider, with_unknown_args=True)
122122
def do_test_argparse_with_list_ns(self, args, extra):
123-
self.stdout.write('{}'.format(args.custom_stuff))
123+
self.stdout.write(f'{args.custom_stuff}')
124124

125125

126126
@pytest.fixture

0 commit comments

Comments
 (0)