Skip to content

Commit e9384ce

Browse files
Use fstrings (#353)
Convert string formatting to f-strings with flynt
1 parent bbdf176 commit e9384ce

File tree

7 files changed

+39
-42
lines changed

7 files changed

+39
-42
lines changed

doc/conf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@
141141
"**": [],
142142
}
143143

144-
html_title = "%s v%s Manual" % (project, version)
144+
html_title = f"{project} v{version} Manual"
145145
html_last_updated_fmt = '%b %d, %Y'
146146

147147
# Add any paths that contain custom static files (such as style sheets) here,

numpydoc/docscrape.py

+10-11
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ class ParseError(Exception):
101101
def __str__(self):
102102
message = self.args[0]
103103
if hasattr(self, 'docstring'):
104-
message = "%s in %r" % (message, self.docstring)
104+
message = f"{message} in {self.docstring!r}"
105105
return message
106106

107107

@@ -154,7 +154,7 @@ def __getitem__(self, key):
154154

155155
def __setitem__(self, key, val):
156156
if key not in self._parsed_data:
157-
self._error_location("Unknown section %s" % key, error=False)
157+
self._error_location(f"Unknown section {key}", error=False)
158158
else:
159159
self._parsed_data[key] = val
160160

@@ -492,11 +492,11 @@ def _str_see_also(self, func_role):
492492
links = []
493493
for func, role in funcs:
494494
if role:
495-
link = ':%s:`%s`' % (role, func)
495+
link = f':{role}:`{func}`'
496496
elif func_role:
497-
link = ':%s:`%s`' % (func_role, func)
497+
link = f':{func_role}:`{func}`'
498498
else:
499-
link = "`%s`_" % func
499+
link = f"`{func}`_"
500500
links.append(link)
501501
link = ', '.join(links)
502502
out += [link]
@@ -519,12 +519,12 @@ def _str_index(self):
519519
default_index = idx.get('default', '')
520520
if default_index:
521521
output_index = True
522-
out += ['.. index:: %s' % default_index]
522+
out += [f'.. index:: {default_index}']
523523
for section, references in idx.items():
524524
if section == 'default':
525525
continue
526526
output_index = True
527-
out += [' :%s: %s' % (section, ', '.join(references))]
527+
out += [f" :{section}: {', '.join(references)}"]
528528
if output_index:
529529
return out
530530
return ''
@@ -583,9 +583,8 @@ def __str__(self):
583583

584584
if self._role:
585585
if self._role not in roles:
586-
print("Warning: invalid role %s" % self._role)
587-
out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''),
588-
func_name)
586+
print(f"Warning: invalid role {self._role}")
587+
out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
589588

590589
out += super().__str__(func_role=self._role)
591590
return out
@@ -606,7 +605,7 @@ class ClassDoc(NumpyDocString):
606605
def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc,
607606
config=None):
608607
if not inspect.isclass(cls) and cls is not None:
609-
raise ValueError("Expected a class or None, but got %r" % cls)
608+
raise ValueError(f"Expected a class or None, but got {cls!r}")
610609
self._cls = cls
611610

612611
if 'sphinx' in sys.modules:

numpydoc/docscrape_sphinx.py

+11-13
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ def _process_param(self, param, desc, fake_autosummary):
138138
# XXX: If changing the following, please check the rendering when param
139139
# ends with '_', e.g. 'word_'
140140
# See https://github.com/numpy/numpydoc/pull/144
141-
display_param = '**%s**' % param
141+
display_param = f'**{param}**'
142142

143143
if not fake_autosummary:
144144
return display_param, desc
@@ -156,14 +156,12 @@ def _process_param(self, param, desc, fake_autosummary):
156156

157157
prefix = getattr(self, '_name', '')
158158
if prefix:
159-
link_prefix = '%s.' % prefix
159+
link_prefix = f'{prefix}.'
160160
else:
161161
link_prefix = ''
162162

163163
# Referenced object has a docstring
164-
display_param = ':obj:`%s <%s%s>`' % (param,
165-
link_prefix,
166-
param)
164+
display_param = f':obj:`{param} <{link_prefix}{param}>`'
167165
if obj_doc:
168166
# Overwrite desc. Take summary logic of autosummary
169167
desc = re.split(r'\n\s*\n', obj_doc.strip(), 1)[0]
@@ -239,11 +237,11 @@ def _str_member_list(self, name):
239237
"""
240238
out = []
241239
if self[name]:
242-
out += ['.. rubric:: %s' % name, '']
240+
out += [f'.. rubric:: {name}', '']
243241
prefix = getattr(self, '_name', '')
244242

245243
if prefix:
246-
prefix = '~%s.' % prefix
244+
prefix = f'~{prefix}.'
247245

248246
autosum = []
249247
others = []
@@ -259,7 +257,7 @@ def _str_member_list(self, name):
259257

260258
if param_obj and pydoc.getdoc(param_obj):
261259
# Referenced object has a docstring
262-
autosum += [" %s%s" % (prefix, param.name)]
260+
autosum += [f" {prefix}{param.name}"]
263261
else:
264262
others.append(param)
265263

@@ -279,7 +277,7 @@ def _str_member_list(self, name):
279277
desc = " ".join(x.strip()
280278
for x in param.desc).strip()
281279
if param.type:
282-
desc = "(%s) %s" % (param.type, desc)
280+
desc = f"({param.type}) {desc}"
283281
out += [fmt % (name, desc)]
284282
out += [hdr]
285283
out += ['']
@@ -316,14 +314,14 @@ def _str_index(self):
316314
if len(idx) == 0:
317315
return out
318316

319-
out += ['.. index:: %s' % idx.get('default', '')]
317+
out += [f".. index:: {idx.get('default', '')}"]
320318
for section, references in idx.items():
321319
if section == 'default':
322320
continue
323321
elif section == 'refguide':
324-
out += [' single: %s' % (', '.join(references))]
322+
out += [f" single: {', '.join(references)}"]
325323
else:
326-
out += [' %s: %s' % (section, ','.join(references))]
324+
out += [f" {section}: {','.join(references)}"]
327325
out += ['']
328326
return out
329327

@@ -343,7 +341,7 @@ def _str_references(self):
343341
m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I)
344342
if m:
345343
items.append(m.group(1))
346-
out += [' ' + ", ".join(["[%s]_" % item for item in items]), '']
344+
out += [' ' + ", ".join([f"[{item}]_" for item in items]), '']
347345
return out
348346

349347
def _str_examples(self):

numpydoc/numpydoc.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,10 @@ def rename_references(app, what, name, obj, options, lines):
6363
for r in references:
6464
new_r = prefix + '-' + r
6565
for i, line in enumerate(lines):
66-
lines[i] = lines[i].replace('[%s]_' % r,
67-
'[%s]_' % new_r)
68-
lines[i] = lines[i].replace('.. [%s]' % r,
69-
'.. [%s]' % new_r)
66+
lines[i] = lines[i].replace(f'[{r}]_',
67+
f'[{new_r}]_')
68+
lines[i] = lines[i].replace(f'.. [{r}]',
69+
f'.. [{new_r}]')
7070

7171

7272
def _is_cite_in_numpydoc_docstring(citation_node):
@@ -119,10 +119,10 @@ def relabel_references(app, doc):
119119
# Sphinx has created pending_xref nodes with [reftext] text.
120120
def matching_pending_xref(node):
121121
return (isinstance(node, pending_xref) and
122-
node[0].astext() == '[%s]' % ref_text)
122+
node[0].astext() == f'[{ref_text}]')
123123

124124
for xref_node in ref.parent.traverse(matching_pending_xref):
125-
xref_node.replace(xref_node[0], Text('[%s]' % new_text))
125+
xref_node.replace(xref_node[0], Text(f'[{new_text}]'))
126126
ref.replace(ref_text, new_text.copy())
127127

128128

@@ -199,11 +199,11 @@ def mangle_docstrings(app, what, name, obj, options, lines):
199199
if (app.config.numpydoc_edit_link and hasattr(obj, '__name__') and
200200
obj.__name__):
201201
if hasattr(obj, '__module__'):
202-
v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__))
202+
v = dict(full_name=f"{obj.__module__}.{obj.__name__}")
203203
else:
204204
v = dict(full_name=obj.__name__)
205205
lines += ['', '.. htmlonly::', '']
206-
lines += [' %s' % x for x in
206+
lines += [f' {x}' for x in
207207
(app.config.numpydoc_edit_link % v).split("\n")]
208208

209209
# call function to replace reference numbers so that there are no

numpydoc/tests/test_validate.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1388,7 +1388,7 @@ def test_bad_docstrings(self, capsys, klass, func, msgs):
13881388
class TestValidatorClass:
13891389
@pytest.mark.parametrize("invalid_name", ["unknown_mod", "unknown_mod.MyClass"])
13901390
def test_raises_for_invalid_module_name(self, invalid_name):
1391-
msg = 'No module can be imported from "{}"'.format(invalid_name)
1391+
msg = f'No module can be imported from "{invalid_name}"'
13921392
with pytest.raises(ImportError, match=msg):
13931393
numpydoc.validate.Validator._load_obj(invalid_name)
13941394

@@ -1398,6 +1398,6 @@ def test_raises_for_invalid_module_name(self, invalid_name):
13981398
def test_raises_for_invalid_attribute_name(self, invalid_name):
13991399
name_components = invalid_name.split(".")
14001400
obj_name, invalid_attr_name = name_components[-2], name_components[-1]
1401-
msg = "'{}' has no attribute '{}'".format(obj_name, invalid_attr_name)
1401+
msg = f"'{obj_name}' has no attribute '{invalid_attr_name}'"
14021402
with pytest.raises(AttributeError, match=msg):
14031403
numpydoc.validate.Validator._load_obj(invalid_name)

numpydoc/validate.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ def _load_obj(name):
164164
else:
165165
break
166166
else:
167-
raise ImportError("No module can be imported " 'from "{}"'.format(name))
167+
raise ImportError(f"No module can be imported from \"{name}\"")
168168

169169
for part in func_parts:
170170
obj = getattr(obj, part)
@@ -288,9 +288,9 @@ def add_stars(param_name, info):
288288
Add stars to *args and **kwargs parameters
289289
"""
290290
if info.kind == inspect.Parameter.VAR_POSITIONAL:
291-
return "*{}".format(param_name)
291+
return f"*{param_name}"
292292
elif info.kind == inspect.Parameter.VAR_KEYWORD:
293-
return "**{}".format(param_name)
293+
return f"**{param_name}"
294294
else:
295295
return param_name
296296

@@ -420,7 +420,7 @@ def _check_desc(desc, code_no_desc, code_no_upper, code_no_period, **kwargs):
420420
# Find and strip out any sphinx directives
421421
desc = "\n".join(desc)
422422
for directive in DIRECTIVES:
423-
full_directive = ".. {}".format(directive)
423+
full_directive = f".. {directive}"
424424
if full_directive in desc:
425425
# Only retain any description before the directive
426426
desc = desc[: desc.index(full_directive)].rstrip("\n")

numpydoc/xref.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def make_xref(param_type, xref_aliases, xref_ignore):
126126
ignore_set = set()
127127
else:
128128
raise TypeError(
129-
"xref_ignore must be a set or 'all', got {}".format(xref_ignore)
129+
f"xref_ignore must be a set or 'all', got {xref_ignore}"
130130
)
131131

132132
if param_type in xref_aliases:
@@ -137,9 +137,9 @@ def make_xref(param_type, xref_aliases, xref_ignore):
137137

138138
if QUALIFIED_NAME_RE.match(link) and link not in ignore_set:
139139
if link != title:
140-
return ':obj:`%s <%s>`' % (title, link)
140+
return f':obj:`{title} <{link}>`'
141141
if wrap_unknown:
142-
return ':obj:`%s`' % link
142+
return f':obj:`{link}`'
143143
return link
144144

145145
def _split_and_apply_re(s, pattern):

0 commit comments

Comments
 (0)