Skip to content

Commit

Permalink
Continue removing .format in favor of f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
dbieber committed Sep 20, 2024
1 parent a888f48 commit d55053a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 48 deletions.
64 changes: 29 additions & 35 deletions fire/helptext.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def _NameSection(component, info, trace=None, verbose=False):
LINE_LENGTH)

if summary:
text = current_command + ' - ' + summary
text = f'{current_command} - {summary}'
else:
text = current_command
return ('NAME', text)
Expand Down Expand Up @@ -340,18 +340,18 @@ def _GetArgsAndFlagsString(spec, metadata):
for arg in args_with_no_defaults]
else:
arg_strings = [
'--{arg}={arg_upper}'.format(
arg=arg, arg_upper=formatting.Underline(arg.upper()))
for arg in args_with_no_defaults]
f'--{arg}={formatting.Underline(arg.upper())}'
for arg in args_with_no_defaults
]
arg_and_flag_strings.extend(arg_strings)

# If there are any arguments that are treated as flags:
if args_with_defaults or spec.kwonlyargs or spec.varkw:
arg_and_flag_strings.append('<flags>')

if spec.varargs:
varargs_string = '[{varargs}]...'.format(
varargs=formatting.Underline(spec.varargs.upper()))
varargs_underlined = formatting.Underline(spec.varargs.upper())
varargs_string = f'[{varargs_underlined}]...'
arg_and_flag_strings.append(varargs_string)

return ' '.join(arg_and_flag_strings)
Expand Down Expand Up @@ -394,7 +394,7 @@ def _GetActionsGroupedByKind(component, verbose=False):
if component_len < 10:
indexes.Add(name=', '.join(str(x) for x in range(component_len)))
else:
indexes.Add(name='0..{max}'.format(max=component_len-1))
indexes.Add(name=f'0..{component_len-1}')

return [groups, commands, values, indexes]

Expand All @@ -409,10 +409,8 @@ def _GetCurrentCommand(trace=None, include_separators=True):


def _CreateOutputSection(name, content):
return """{name}
{content}""".format(
name=formatting.Bold(name),
content=formatting.Indent(content, SECTION_INDENTATION))
return f"""{formatting.Bold(name)}
{formatting.Indent(content, SECTION_INDENTATION)}"""


def _CreateArgItem(arg, docstring_info, spec):
Expand All @@ -423,7 +421,7 @@ def _CreateArgItem(arg, docstring_info, spec):
docstring_info: A docstrings.DocstringInfo namedtuple with information about
the containing function's docstring.
spec: An instance of fire.inspectutils.FullArgSpec, containing type and
default information about the arguments to a callable.
default information about the arguments to a callable.
Returns:
A string to be used in constructing the help screen for the function.
Expand All @@ -438,7 +436,7 @@ def _CreateArgItem(arg, docstring_info, spec):
arg_string = formatting.BoldUnderline(arg.upper())

arg_type = _GetArgType(arg, spec)
arg_type = 'Type: {}'.format(arg_type) if arg_type else ''
arg_type = f'Type: {arg_type}' if arg_type else ''
available_space = max_str_length - len(arg_type)
arg_type = (
formatting.EllipsisTruncate(arg_type, available_space, max_str_length))
Expand Down Expand Up @@ -483,7 +481,7 @@ def _CreateFlagItem(flag, docstring_info, spec, required=False,
flag_string += ' (required)'
if short_arg:
short_flag = flag[0]
flag_string = f'-{short_flag}, ' + flag_string
flag_string = f'-{short_flag}, {flag_string}'

arg_type = _GetArgType(flag, spec)
arg_default = _GetArgDefault(flag, spec)
Expand Down Expand Up @@ -559,15 +557,15 @@ def _GetArgDefault(flag, spec):
def _CreateItem(name, description, indent=2):
if not description:
return name
return """{name}
{description}""".format(name=name,
description=formatting.Indent(description, indent))
description = formatting.Indent(description, indent)
return f"""{name}
{description}"""


def _GetArgDescription(name, docstring_info):
if docstring_info.args:
for arg_in_docstring in docstring_info.args:
if arg_in_docstring.name in (name, '*' + name, '**' + name):
if arg_in_docstring.name in (name, f'*{name}', f'**{name}'):
return arg_in_docstring.description
return None

Expand Down Expand Up @@ -613,9 +611,9 @@ def _ValuesUsageDetailsSection(component, values):


def _NewChoicesSection(name, choices):
name_formatted = formatting.Bold(formatting.Underline(name))
return _CreateItem(
'{name} is one of the following:'.format(
name=formatting.Bold(formatting.Underline(name))),
f'{name_formatted} is one of the following:',
'\n' + '\n\n'.join(choices),
indent=1)

Expand All @@ -631,11 +629,6 @@ def UsageText(component, trace=None, verbose=False):
Returns:
String suitable for display in an error screen.
"""
output_template = """Usage: {continued_command}
{availability_lines}
For detailed information on this command, run:
{help_command}"""

# Get the command so far:
if trace:
command = trace.GetCommand()
Expand Down Expand Up @@ -679,15 +672,16 @@ def UsageText(component, trace=None, verbose=False):
+ '--help'
)

return output_template.format(
continued_command=continued_command,
availability_lines=''.join(availability_lines),
help_command=help_command)
return f"""Usage: {continued_command}
{''.join(availability_lines)}
For detailed information on this command, run:
{help_command}"""


def _GetPossibleActionsUsageString(possible_actions):
if possible_actions:
return '<{actions}>'.format(actions='|'.join(possible_actions))
actions_str = '|'.join(possible_actions)
return f'<{actions_str}>'
return None


Expand All @@ -696,7 +690,7 @@ def _UsageAvailabilityLines(actions_grouped_by_kind):
for action_group in actions_grouped_by_kind:
if action_group.members:
availability_line = _CreateAvailabilityLine(
header='available {plural}:'.format(plural=action_group.plural),
header=f'available {action_group.plural}:',
items=action_group.names
)
availability_lines.append(availability_line)
Expand All @@ -712,7 +706,7 @@ def _GetCallableUsageItems(spec, metadata):
accepts_positional_args = metadata.get(decorators.ACCEPTS_POSITIONAL_ARGS)

if not accepts_positional_args:
items = ['--{arg}={upper}'.format(arg=arg, upper=arg.upper())
items = [f'--{arg}={arg.upper()}'
for arg in args_with_no_defaults]
else:
items = [arg.upper() for arg in args_with_no_defaults]
Expand All @@ -722,7 +716,7 @@ def _GetCallableUsageItems(spec, metadata):
items.append('<flags>')

if spec.varargs:
items.append('[{varargs}]...'.format(varargs=spec.varargs.upper()))
items.append(f'[{spec.varargs.upper()}]...')

return items

Expand All @@ -737,10 +731,10 @@ def _GetCallableAvailabilityLines(spec):
args_with_defaults = spec.args[len(spec.args) - len(spec.defaults):]

# TODO(dbieber): Handle args_with_no_defaults if not accepts_positional_args.
optional_flags = [('--' + flag) for flag in itertools.chain(
optional_flags = [f'--{flag}' for flag in itertools.chain(
args_with_defaults, _KeywordOnlyArguments(spec, required=False))]
required_flags = [
('--' + flag) for flag in _KeywordOnlyArguments(spec, required=True)
f'--{flag}' for flag in _KeywordOnlyArguments(spec, required=True)
]

# Flags section:
Expand Down
11 changes: 6 additions & 5 deletions fire/interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,17 @@ def _AvailableString(variables, verbose=False):
lists = [
('Modules', modules),
('Objects', other)]
liststrs = []
list_strs = []
for name, varlist in lists:
if varlist:
liststrs.append(
'{name}: {items}'.format(name=name, items=', '.join(sorted(varlist))))
items_str = ', '.join(sorted(varlist))
list_strs.append(f'{name}: {items_str}')

lists_str = '\n'.join(list_strs)
return (
'Fire is starting a Python REPL with the following objects:\n'
'{liststrs}\n'
).format(liststrs='\n'.join(liststrs))
f'{lists_str}\n'
)


def _EmbedIPython(variables, argv=None):
Expand Down
13 changes: 5 additions & 8 deletions fire/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,7 @@ def NeedsSeparator(self):
def __str__(self):
lines = []
for index, element in enumerate(self.elements):
line = '{index}. {trace_string}'.format(
index=index + 1,
trace_string=element,
)
line = f'{index + 1}. {element}'
lines.append(line)
return '\n'.join(lines)

Expand Down Expand Up @@ -261,7 +258,7 @@ def __init__(self,
Args:
component: The result of this element of the trace.
action: The type of action (eg instantiating a class) taking place.
action: The type of action (e.g. instantiating a class) taking place.
target: (string) The name of the component being acted upon.
args: The args consumed by the represented action.
filename: The file in which the action is defined, or None if N/A.
Expand Down Expand Up @@ -301,11 +298,11 @@ def __str__(self):
# Format is: {action} "{target}" ({filename}:{lineno})
string = self._action
if self._target is not None:
string += ' "{target}"'.format(target=self._target)
string += f' "{self._target}"'
if self._filename is not None:
path = self._filename
if self._lineno is not None:
path += ':{lineno}'.format(lineno=self._lineno)
path += f':{self._lineno}'

string += ' ({path})'.format(path=path)
string += f' ({path})'
return string

0 comments on commit d55053a

Please sign in to comment.