Skip to content

Commit 83a5ec0

Browse files
kmvanbruntanselor
authored andcommitted
Updated main code to use f-strings
1 parent e8b6456 commit 83a5ec0

File tree

9 files changed

+125
-162
lines changed

9 files changed

+125
-162
lines changed

cmd2/ansi.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def __str__(self) -> str:
7878
"""
7979
Return ANSI color sequence instead of enum name
8080
This is helpful when using a ColorBase in an f-string or format() call
81-
e.g. my_str = "{}hello{}".format(fg.blue, fg.reset)
81+
e.g. my_str = f"{fg.blue}hello{fg.reset}"
8282
"""
8383
return str(self.value)
8484

@@ -244,7 +244,7 @@ def fg_lookup(fg_name: Union[str, fg]) -> str:
244244
try:
245245
ansi_escape = fg[fg_name.lower()].value
246246
except KeyError:
247-
raise ValueError('Foreground color {!r} does not exist; must be one of: {}'.format(fg_name, fg.colors()))
247+
raise ValueError(f"Foreground color '{fg_name}' does not exist; must be one of: {fg.colors()}")
248248
return str(ansi_escape)
249249

250250

@@ -262,7 +262,7 @@ def bg_lookup(bg_name: Union[str, bg]) -> str:
262262
try:
263263
ansi_escape = bg[bg_name.lower()].value
264264
except KeyError:
265-
raise ValueError('Background color {!r} does not exist; must be one of: {}'.format(bg_name, bg.colors()))
265+
raise ValueError(f"Background color '{bg_name}' does not exist; must be one of: {bg.colors()}")
266266
return str(ansi_escape)
267267

268268

@@ -274,14 +274,14 @@ def style(
274274
bg: Union[str, bg] = '',
275275
bold: bool = False,
276276
dim: bool = False,
277-
underline: bool = False
277+
underline: bool = False,
278278
) -> str:
279279
"""
280280
Apply ANSI colors and/or styles to a string and return it.
281281
The styling is self contained which means that at the end of the string reset code(s) are issued
282282
to undo whatever styling was done at the beginning.
283283
284-
:param text: Any object compatible with str.format()
284+
:param text: text to format (anything convertible to a str)
285285
:param fg: foreground color. Relies on `fg_lookup()` to retrieve ANSI escape based on name or enum.
286286
Defaults to no color.
287287
:param bg: background color. Relies on `bg_lookup()` to retrieve ANSI escape based on name or enum.
@@ -298,7 +298,7 @@ def style(
298298
removals: List[str] = []
299299

300300
# Convert the text object into a string if it isn't already one
301-
text_formatted = "{}".format(text)
301+
text_formatted = str(text)
302302

303303
# Process the style settings
304304
if fg:

cmd2/argparse_custom.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -256,18 +256,16 @@ def generate_range_error(range_min: int, range_max: Union[int, float]) -> str:
256256
err_str = "expected "
257257

258258
if range_max == constants.INFINITY:
259-
err_str += "at least {} argument".format(range_min)
260-
261-
if range_min != 1:
262-
err_str += "s"
259+
plural = '' if range_min == 1 else 's'
260+
err_str += f"at least {range_min}"
263261
else:
262+
plural = '' if range_max == 1 else 's'
264263
if range_min == range_max:
265-
err_str += "{} argument".format(range_min)
264+
err_str += f"{range_min}"
266265
else:
267-
err_str += "{} to {} argument".format(range_min, range_max)
266+
err_str += f"{range_min} to {range_max}"
268267

269-
if range_max != 1:
270-
err_str += "s"
268+
err_str += f" argument{plural}"
271269

272270
return err_str
273271

@@ -600,7 +598,7 @@ def _get_nargs_pattern_wrapper(self: argparse.ArgumentParser, action: argparse.A
600598
else:
601599
range_max = nargs_range[1]
602600

603-
nargs_pattern = '(-*A{{{},{}}}-*)'.format(nargs_range[0], range_max)
601+
nargs_pattern = f'(-*A{{{nargs_range[0]},{range_max}}}-*)'
604602

605603
# if this is an optional action, -- is not allowed
606604
if action.option_strings:
@@ -881,9 +879,9 @@ def _format_args(self, action: argparse.Action, default_metavar: Union[str, Tupl
881879
nargs_range = getattr(action, ATTR_NARGS_RANGE, None)
882880
if nargs_range is not None:
883881
if nargs_range[1] == constants.INFINITY:
884-
range_str = '{}+'.format(nargs_range[0])
882+
range_str = f'{nargs_range[0]}+'
885883
else:
886-
range_str = '{}..{}'.format(nargs_range[0], nargs_range[1])
884+
range_str = f'{nargs_range[0]}..{nargs_range[1]}'
887885

888886
return '{}{{{}}}'.format('%s' % metavar_formatter(1), range_str)
889887

@@ -960,7 +958,7 @@ def error(self, message: str) -> NoReturn:
960958

961959
self.print_usage(sys.stderr)
962960
formatted_message = ansi.style_error(formatted_message)
963-
self.exit(2, '{}\n\n'.format(formatted_message))
961+
self.exit(2, f'{formatted_message}\n\n')
964962

965963
# noinspection PyProtectedMember
966964
def format_help(self) -> str:

cmd2/cmd2.py

Lines changed: 89 additions & 118 deletions
Large diffs are not rendered by default.

cmd2/decorators.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def with_argparser(
298298
>>> @cmd2.with_argparser(parser, preserve_quotes=True)
299299
>>> def do_argprint(self, args):
300300
>>> "Print the options and argument list this options command was called with."
301-
>>> self.poutput('args: {!r}'.format(args))
301+
>>> self.poutput(f'args: {args!r}')
302302
303303
:Example with unknown args:
304304
@@ -311,8 +311,8 @@ def with_argparser(
311311
>>> @cmd2.with_argparser(parser, with_unknown_args=True)
312312
>>> def do_argprint(self, args, unknown):
313313
>>> "Print the options and argument list this options command was called with."
314-
>>> self.poutput('args: {!r}'.format(args))
315-
>>> self.poutput('unknowns: {}'.format(unknown))
314+
>>> self.poutput(f'args: {args!r}')
315+
>>> self.poutput(f'unknowns: {unknown}')
316316
317317
"""
318318
import functools

cmd2/parsing.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def command_and_args(self) -> str:
167167
excluded, as are any command terminators.
168168
"""
169169
if self.command and self.args:
170-
rtn = '{} {}'.format(self.command, self.args)
170+
rtn = f'{self.command} {self.args}'
171171
elif self.command:
172172
# there were no arguments to the command
173173
rtn = self.command
@@ -286,7 +286,7 @@ def __init__(
286286
# join them up with a pipe
287287
second_group = '|'.join(second_group_items)
288288
# build the regular expression
289-
expr = r'\A\s*(\S*?)({})'.format(second_group)
289+
expr = rf'\A\s*(\S*?)({second_group})'
290290
self._command_pattern = re.compile(expr)
291291

292292
def is_valid_command(self, word: str, *, is_subcommand: bool = False) -> Tuple[bool, str]:
@@ -306,12 +306,12 @@ def is_valid_command(self, word: str, *, is_subcommand: bool = False) -> Tuple[b
306306
checkit = '>'
307307
valid, errmsg = statement_parser.is_valid_command(checkit)
308308
if not valid:
309-
errmsg = "alias: {}".format(errmsg)
309+
errmsg = f"alias: {errmsg}"
310310
"""
311311
valid = False
312312

313313
if not isinstance(word, str):
314-
return False, 'must be a string. Received {} instead'.format(str(type(word))) # type: ignore[unreachable]
314+
return False, f'must be a string. Received {str(type(word))} instead' # type: ignore[unreachable]
315315

316316
if not word:
317317
return False, 'cannot be an empty string'

cmd2/table_creator.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def __init__(
6666
header_vert_align: VerticalAlignment = VerticalAlignment.BOTTOM,
6767
data_horiz_align: HorizontalAlignment = HorizontalAlignment.LEFT,
6868
data_vert_align: VerticalAlignment = VerticalAlignment.TOP,
69-
max_data_lines: Union[int, float] = constants.INFINITY
69+
max_data_lines: Union[int, float] = constants.INFINITY,
7070
) -> None:
7171
"""
7272
Column initializer
@@ -408,7 +408,7 @@ def generate_row(
408408
fill_char: str = SPACE,
409409
pre_line: str = EMPTY,
410410
inter_cell: str = (2 * SPACE),
411-
post_line: str = EMPTY
411+
post_line: str = EMPTY,
412412
) -> str:
413413
"""
414414
Generate a header or data table row
@@ -462,7 +462,7 @@ def __init__(self) -> None:
462462
validation_dict = {'fill_char': fill_char, 'pre_line': pre_line, 'inter_cell': inter_cell, 'post_line': post_line}
463463
for key, val in validation_dict.items():
464464
if ansi.style_aware_wcswidth(val) == -1:
465-
raise (ValueError("{} contains an unprintable character".format(key)))
465+
raise ValueError(f"{key} contains an unprintable character")
466466

467467
# Number of lines this row uses
468468
total_lines = 0
@@ -556,7 +556,7 @@ def __init__(self, cols: Sequence[Column], *, tab_width: int = 4, divider_char:
556556

557557
divider_char_width = ansi.style_aware_wcswidth(divider_char)
558558
if divider_char_width == -1:
559-
raise (ValueError("Divider character is an unprintable character"))
559+
raise ValueError("Divider character is an unprintable character")
560560

561561
super().__init__(cols, tab_width=tab_width)
562562
self.divider_char = divider_char
@@ -855,7 +855,7 @@ def __init__(
855855
column_borders: bool = True,
856856
padding: int = 1,
857857
bg_odd: Optional[ansi.bg] = None,
858-
bg_even: Optional[ansi.bg] = ansi.bg.bright_black
858+
bg_even: Optional[ansi.bg] = ansi.bg.bright_black,
859859
) -> None:
860860
"""
861861
AlternatingTable initializer

cmd2/transcript.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,7 @@ def _test_transcript(self, fname: str, transcript: Iterator[str]) -> None:
100100
try:
101101
line = next(transcript)
102102
except StopIteration as exc:
103-
msg = 'Transcript broke off while reading command beginning at line {} with\n{}'.format(
104-
line_num, command_parts[0]
105-
)
103+
msg = f'Transcript broke off while reading command beginning at line {line_num} with\n{command_parts[0]}'
106104
raise StopIteration(msg) from exc
107105
line_num += 1
108106
command = ''.join(command_parts)
@@ -112,9 +110,7 @@ def _test_transcript(self, fname: str, transcript: Iterator[str]) -> None:
112110
stop_msg = 'Command indicated application should quit, but more commands in transcript'
113111
# Read the expected result from transcript
114112
if ansi.strip_style(line).startswith(self.cmdapp.visible_prompt):
115-
message = '\nFile {}, line {}\nCommand was:\n{}\nExpected: (nothing)\nGot:\n{}\n'.format(
116-
fname, line_num, command, result
117-
)
113+
message = f'\nFile {fname}, line {line_num}\nCommand was:\n{command}\nExpected: (nothing)\nGot:\n{result}\n'
118114
self.assertTrue(not (result.strip()), message)
119115
# If the command signaled the application to quit there should be no more commands
120116
self.assertFalse(stop, stop_msg)
@@ -136,9 +132,7 @@ def _test_transcript(self, fname: str, transcript: Iterator[str]) -> None:
136132
# transform the expected text into a valid regular expression
137133
expected = ''.join(expected_parts)
138134
expected = self._transform_transcript_expected(expected)
139-
message = '\nFile {}, line {}\nCommand was:\n{}\nExpected:\n{}\nGot:\n{}\n'.format(
140-
fname, line_num, command, expected, result
141-
)
135+
message = f'\nFile {fname}, line {line_num}\nCommand was:\n{command}\nExpected:\n{expected}\nGot:\n{result}\n'
142136
self.assertTrue(re.match(expected, result, re.MULTILINE | re.DOTALL), message)
143137

144138
def _transform_transcript_expected(self, s: str) -> str:

cmd2/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ def write(self, s: str) -> None:
474474
:param s: String to write to the stream
475475
"""
476476
if not isinstance(s, str):
477-
raise TypeError('write() argument must be str, not {}'.format(type(s)))
477+
raise TypeError(f'write() argument must be str, not {type(s)}')
478478

479479
if not self.pause_storage:
480480
self.buffer.byte_buf += s.encode(encoding=self.encoding, errors=self.errors)
@@ -554,7 +554,7 @@ def __init__(self, std_sim_instance: StdSim) -> None:
554554
def write(self, b: bytes) -> None:
555555
"""Add bytes to internal bytes buffer and if echo is True, echo contents to inner stream."""
556556
if not isinstance(b, bytes):
557-
raise TypeError('a bytes-like object is required, not {}'.format(type(b)))
557+
raise TypeError(f'a bytes-like object is required, not {type(b)}')
558558
if not self.std_sim_instance.pause_storage:
559559
self.byte_buf += b
560560
if self.std_sim_instance.echo:

tests/test_cmd2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -704,7 +704,7 @@ def _expected_no_editor_error():
704704

705705
expected_text = normalize(
706706
"""
707-
EXCEPTION of type '{}' occurred with message: 'Please use 'set editor' to specify your text editing program of choice.'
707+
EXCEPTION of type '{}' occurred with message: Please use 'set editor' to specify your text editing program of choice.
708708
To enable full traceback, run the following command: 'set debug true'
709709
""".format(
710710
expected_exception
@@ -1986,7 +1986,7 @@ def test_macro_usage_with_missing_args(base_app):
19861986

19871987
# Run the macro
19881988
out, err = run_cmd(base_app, 'fake arg1')
1989-
assert "expects at least 2 argument(s)" in err[0]
1989+
assert "expects at least 2 arguments" in err[0]
19901990

19911991

19921992
def test_macro_usage_with_exta_args(base_app):
@@ -2018,7 +2018,7 @@ def test_macro_create_with_unicode_numbered_arg(base_app):
20182018

20192019
# Run the macro
20202020
out, err = run_cmd(base_app, 'fake')
2021-
assert "expects at least 1 argument(s)" in err[0]
2021+
assert "expects at least 1 argument" in err[0]
20222022

20232023

20242024
def test_macro_create_with_missing_unicode_arg_nums(base_app):

0 commit comments

Comments
 (0)