Skip to content

Commit e5e33ad

Browse files
authored
chore: cleanup string.format to f-strings (#432)
* chore: cleanup string.format to f-strings * chore: fix cases where fstrings are not possible
1 parent 637e7cf commit e5e33ad

File tree

4 files changed

+27
-28
lines changed

4 files changed

+27
-28
lines changed

packages/gcp-sphinx-docfx-yaml/docfx_yaml/extension.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ def _resolve_reference_in_module_summary(pattern, lines):
355355

356356
# Check to see if we should create an xref for it.
357357
if 'google.cloud' in matched_str:
358-
new_line = new_line.replace(matched_str, '<xref uid=\"{}\">{}</xref>'.format(xref, ref_name))
358+
new_line = new_line.replace(matched_str, f'<xref uid="{xref}">{ref_name}</xref>')
359359
# If it not a Cloud library, don't create xref for it.
360360
else:
361361
# Carefully extract the original uid
@@ -364,7 +364,7 @@ def _resolve_reference_in_module_summary(pattern, lines):
364364
ref_name = matched_str[index+1:-1]
365365
else:
366366
ref_name = matched_str[1:]
367-
new_line = new_line.replace(matched_str, '`{}`'.format(ref_name))
367+
new_line = new_line.replace(matched_str, f'`{ref_name}`')
368368

369369
new_lines.append(new_line)
370370
return new_lines, xrefs
@@ -602,8 +602,7 @@ def _parse_docstring_summary(
602602

603603
# Extracts the notice content and format it.
604604
elif keyword and keyword in NOTICES:
605-
summary_parts.append(notice_open_tag.format(
606-
notice_tag=keyword, notice_name=NOTICES[keyword]))
605+
summary_parts.append(f'<aside class="{keyword}">\n<b>{NOTICES[keyword]}:</b>')
607606
tab_space = -1
608607
notice_body = []
609608
parts = [split_part for split_part in part.split("\n") if split_part][1:]
@@ -1019,12 +1018,12 @@ def _update_friendly_package_name(path):
10191018
lines = inspect.getdoc(obj)
10201019
lines = lines.split("\n") if lines else []
10211020
except TypeError as e:
1022-
print("couldn't getdoc from method, function: {}".format(e))
1021+
print(f"couldn't getdoc from method, function: {e}")
10231022
elif _type in [PROPERTY]:
10241023
lines = inspect.getdoc(obj)
10251024
lines = lines.split("\n") if lines else []
10261025
except TypeError as e:
1027-
print("Can't get argspec for {}: {}. {}".format(type(obj), name, e))
1026+
print(f"Can't get argspec for {type(obj)}: {name}. {e}")
10281027

10291028
if name in app.env.docfx_signature_funcs_methods:
10301029
sig = app.env.docfx_signature_funcs_methods[name]
@@ -1064,9 +1063,9 @@ def _update_friendly_package_name(path):
10641063
except (TypeError, OSError):
10651064
# TODO: remove this once there is full handler for property
10661065
if _type in [PROPERTY]:
1067-
print("Skip inspecting for property: {}".format(name))
1066+
print(f"Skip inspecting for property: {name}")
10681067
else:
1069-
print("Can't inspect type {}: {}".format(type(obj), name))
1068+
print(f"Can't inspect type {type(obj)}: {name}")
10701069
path = None
10711070
start_line = None
10721071

@@ -1246,11 +1245,11 @@ def process_docstring(app, _type, name, obj, options, lines):
12461245

12471246
if _type == FUNCTION and app.config.autodoc_functions:
12481247
if datam['uid'] is None:
1249-
raise ValueError("Issue with {0} (name={1})".format(datam, name))
1248+
raise ValueError(f"Issue with {datam} (name={name})")
12501249
if cls is None:
12511250
cls = name
12521251
if cls is None:
1253-
raise ValueError("cls is None for name='{1}' {0}".format(datam, name))
1252+
raise ValueError(f"cls is None for name='{name}' {datam}")
12541253
if cls not in app.env.docfx_yaml_functions:
12551254
app.env.docfx_yaml_functions[cls] = [datam]
12561255
else:

packages/gcp-sphinx-docfx-yaml/docfx_yaml/extract_nodes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def extract_yaml(app, doctree, ignore_patterns):
135135
try:
136136
uid = desc_node[0].attributes['ids'][0]
137137
except Exception:
138-
uid = '{module}.{full_name}'.format(module=module, full_name=full_name)
138+
uid = f'{module}.{full_name}'
139139
print('Non-standard id: %s' % uid)
140140
name = desc_node[0].attributes['names'][0]
141141
source = desc_node[0].source
@@ -150,7 +150,7 @@ def extract_yaml(app, doctree, ignore_patterns):
150150
args = []
151151

152152
if args:
153-
full_name += "({args})".format(args=', '.join(args))
153+
full_name += f"({', '.join(args)})"
154154

155155
datam = {
156156
'module': str(module),

packages/gcp-sphinx-docfx-yaml/docfx_yaml/monkeypatch.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def _get_desc_data(node):
4545
try:
4646
uid = node[0].attributes['ids'][0]
4747
except Exception:
48-
uid = '{module}.{full_name}'.format(module=module, full_name=full_name)
48+
uid = f'{module}.{full_name}'
4949
print('Non-standard id: %s' % uid)
5050
return full_name, uid
5151

packages/gcp-sphinx-docfx-yaml/docfx_yaml/writer.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -581,8 +581,8 @@ def depart_table(self, node):
581581
colwidths = self.table[0]
582582
realwidths = colwidths[:]
583583
separator = 0
584-
self.add_text('<!-- {} -->'.format(node.tagname))
585-
# self.add_text('<!-- {} -->'.format(json.dumps(self.table)))
584+
self.add_text(f'<!-- {node.tagname} -->')
585+
# self.add_text(f'<!-- {json.dumps(self.table)} -->')
586586

587587
# don't allow paragraphs in table cells for now
588588
# for line in lines:
@@ -642,13 +642,13 @@ def visit_image(self, node):
642642
try:
643643
image_name = '/'.join(node.attributes['uri'].split('/')[node.attributes['uri'].split('/').index('_static')-1:])
644644
except ValueError as e:
645-
print("Image not found where expected {}".format(node.attributes['uri']))
645+
print(f"Image not found where expected {node.attributes['uri']}")
646646
raise nodes.SkipNode
647647
image_name = ''.join(image_name.split())
648648
self.new_state(0)
649649
if 'alt' in node.attributes:
650-
self.add_text('![{}]({})'.format(node['alt'], image_name) + self.nl)
651-
self.add_text('![image]({})'.format(image_name) + self.nl)
650+
self.add_text(f'![{node["alt"]}]({image_name})' + self.nl)
651+
self.add_text(f'![image]({image_name})' + self.nl)
652652
self.end_state(False)
653653
raise nodes.SkipNode
654654

@@ -793,7 +793,7 @@ def depart_alert_box(self, node):
793793
self.clear_last_state()
794794
MarkdownTranslator.resolve_reference_in_node(node)
795795
lines = node.astext().split('\n')
796-
quoteLines = ['> {0}\n>'.format(line) for line in lines]
796+
quoteLines = [f'> {line}\n>' for line in lines]
797797
mdStr = '\n> [!{0}]\n{1}'.format(name, '\n'.join(quoteLines))
798798
self.add_text(mdStr)
799799
return depart_alert_box
@@ -849,18 +849,18 @@ def visit_literal_block(self, node):
849849
include_language = (('-' + include_language) if (include_language is not None) else '')
850850
include_caption = (('"' + include_caption + '"') if (include_caption is not None) else '')
851851

852-
self.add_text('<!--[!code{}[Main]({} {})]-->'.format(include_language, relative_path, include_caption))
852+
self.add_text(f'<!--[!code{include_language}[Main]({relative_path} {include_caption})]-->')
853853
except KeyError as e:
854854
pass
855855
except ValueError as e:
856856
pass
857857

858858
self.new_state(0)
859-
self.add_text('<!-- {} {} -->'.format(node.tagname, json.dumps(node.attributes)))
859+
self.add_text(f'<!-- {node.tagname} {json.dumps(node.attributes)} -->')
860860
self.end_state(wrap=False)
861861

862862
if 'language' in node.attributes:
863-
self.add_text('````{}'.format(node.attributes['language']))
863+
self.add_text(f'````{node.attributes["language"]}')
864864
else:
865865
self.add_text('````')
866866
self.new_state()
@@ -919,7 +919,7 @@ def depart_paragraph(self, node):
919919
def visit_target(self, node):
920920
if node.hasattr('refid'):
921921
self.new_state(0)
922-
self.add_text('<a name={}></a>'.format(node.attributes['refid']))
922+
self.add_text(f'<a name={node.attributes["refid"]}></a>')
923923
self.end_state()
924924
raise nodes.SkipNode
925925

@@ -934,7 +934,7 @@ def visit_substitution_definition(self, node):
934934

935935
def visit_pending_xref(self, node):
936936
if 'refdomain' in node.attributes and node.attributes['refdomain'] == 'py':
937-
self.add_text('<xref:{}>'.format(node.attributes['reftarget']))
937+
self.add_text(f'<xref:{node.attributes["reftarget"]}>')
938938
raise nodes.SkipNode
939939

940940
def depart_pending_xref(self, node):
@@ -946,10 +946,10 @@ def _resolve_reference(cls, node):
946946
raw_ref_tilde_template = ":class:`~{0}`"
947947
raw_ref_template = ":class:`{0}`"
948948
if 'refid' in node.attributes:
949-
ref_string = cls.xref_template.format(node.attributes['refid'])
949+
ref_string = f'<xref:{node.attributes["refid"]}>'
950950
elif 'refuri' in node.attributes:
951951
if 'http' in node.attributes['refuri'] or node.attributes['refuri'][0] == '/':
952-
ref_string = '[{}]({})'.format(node.astext(), node.attributes['refuri'])
952+
ref_string = f'[{node.astext()}]({node.attributes["refuri"]})'
953953
else:
954954
# only use id in class and func refuri if its id exists
955955
# otherwise, remove '.html#' in refuri
@@ -971,7 +971,7 @@ def _resolve_reference(cls, node):
971971
else:
972972
ref_string = cls.xref_template.format(node.attributes['refuri'])
973973
else:
974-
ref_string = '{}<!-- {} -->'.format(node.tagname, json.dumps(node.attributes))
974+
ref_string = f'{node.tagname}<!-- {json.dumps(node.attributes)} -->'
975975

976976
return ref_string
977977

@@ -1126,4 +1126,4 @@ def depart_substitution_reference(self, node):
11261126
depart_remarks = remarks.depart_remarks
11271127

11281128
def unknown_visit(self, node):
1129-
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
1129+
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)

0 commit comments

Comments
 (0)