From e9384ce346359cbec556454ae69c1af44d6a9017 Mon Sep 17 00:00:00 2001 From: Jarrod Millman Date: Mon, 10 Jan 2022 13:46:29 -0800 Subject: Use fstrings (#353) Convert string formatting to f-strings with flynt --- doc/conf.py | 2 +- numpydoc/docscrape.py | 21 ++++++++++----------- numpydoc/docscrape_sphinx.py | 24 +++++++++++------------- numpydoc/numpydoc.py | 16 ++++++++-------- numpydoc/tests/test_validate.py | 4 ++-- numpydoc/validate.py | 8 ++++---- numpydoc/xref.py | 6 +++--- 7 files changed, 39 insertions(+), 42 deletions(-) diff --git a/doc/conf.py b/doc/conf.py index 2fa9477..ad142da 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -141,7 +141,7 @@ html_sidebars = { "**": [], } -html_title = "%s v%s Manual" % (project, version) +html_title = f"{project} v{version} Manual" html_last_updated_fmt = '%b %d, %Y' # Add any paths that contain custom static files (such as style sheets) here, diff --git a/numpydoc/docscrape.py b/numpydoc/docscrape.py index 0127675..f0e42eb 100644 --- a/numpydoc/docscrape.py +++ b/numpydoc/docscrape.py @@ -101,7 +101,7 @@ class ParseError(Exception): def __str__(self): message = self.args[0] if hasattr(self, 'docstring'): - message = "%s in %r" % (message, self.docstring) + message = f"{message} in {self.docstring!r}" return message @@ -154,7 +154,7 @@ class NumpyDocString(Mapping): def __setitem__(self, key, val): if key not in self._parsed_data: - self._error_location("Unknown section %s" % key, error=False) + self._error_location(f"Unknown section {key}", error=False) else: self._parsed_data[key] = val @@ -492,11 +492,11 @@ class NumpyDocString(Mapping): links = [] for func, role in funcs: if role: - link = ':%s:`%s`' % (role, func) + link = f':{role}:`{func}`' elif func_role: - link = ':%s:`%s`' % (func_role, func) + link = f':{func_role}:`{func}`' else: - link = "`%s`_" % func + link = f"`{func}`_" links.append(link) link = ', '.join(links) out += [link] @@ -519,12 +519,12 @@ class NumpyDocString(Mapping): default_index = idx.get('default', '') if default_index: output_index = True - out += ['.. index:: %s' % default_index] + out += [f'.. index:: {default_index}'] for section, references in idx.items(): if section == 'default': continue output_index = True - out += [' :%s: %s' % (section, ', '.join(references))] + out += [f" :{section}: {', '.join(references)}"] if output_index: return out return '' @@ -583,9 +583,8 @@ class FunctionDoc(NumpyDocString): if self._role: if self._role not in roles: - print("Warning: invalid role %s" % self._role) - out += '.. %s:: %s\n \n\n' % (roles.get(self._role, ''), - func_name) + print(f"Warning: invalid role {self._role}") + out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n" out += super().__str__(func_role=self._role) return out @@ -606,7 +605,7 @@ class ClassDoc(NumpyDocString): def __init__(self, cls, doc=None, modulename='', func_doc=FunctionDoc, config=None): if not inspect.isclass(cls) and cls is not None: - raise ValueError("Expected a class or None, but got %r" % cls) + raise ValueError(f"Expected a class or None, but got {cls!r}") self._cls = cls if 'sphinx' in sys.modules: diff --git a/numpydoc/docscrape_sphinx.py b/numpydoc/docscrape_sphinx.py index afb5c33..5ded4f0 100644 --- a/numpydoc/docscrape_sphinx.py +++ b/numpydoc/docscrape_sphinx.py @@ -138,7 +138,7 @@ class SphinxDocString(NumpyDocString): # XXX: If changing the following, please check the rendering when param # ends with '_', e.g. 'word_' # See https://github.com/numpy/numpydoc/pull/144 - display_param = '**%s**' % param + display_param = f'**{param}**' if not fake_autosummary: return display_param, desc @@ -156,14 +156,12 @@ class SphinxDocString(NumpyDocString): prefix = getattr(self, '_name', '') if prefix: - link_prefix = '%s.' % prefix + link_prefix = f'{prefix}.' else: link_prefix = '' # Referenced object has a docstring - display_param = ':obj:`%s <%s%s>`' % (param, - link_prefix, - param) + display_param = f':obj:`{param} <{link_prefix}{param}>`' if obj_doc: # Overwrite desc. Take summary logic of autosummary desc = re.split(r'\n\s*\n', obj_doc.strip(), 1)[0] @@ -239,11 +237,11 @@ class SphinxDocString(NumpyDocString): """ out = [] if self[name]: - out += ['.. rubric:: %s' % name, ''] + out += [f'.. rubric:: {name}', ''] prefix = getattr(self, '_name', '') if prefix: - prefix = '~%s.' % prefix + prefix = f'~{prefix}.' autosum = [] others = [] @@ -259,7 +257,7 @@ class SphinxDocString(NumpyDocString): if param_obj and pydoc.getdoc(param_obj): # Referenced object has a docstring - autosum += [" %s%s" % (prefix, param.name)] + autosum += [f" {prefix}{param.name}"] else: others.append(param) @@ -279,7 +277,7 @@ class SphinxDocString(NumpyDocString): desc = " ".join(x.strip() for x in param.desc).strip() if param.type: - desc = "(%s) %s" % (param.type, desc) + desc = f"({param.type}) {desc}" out += [fmt % (name, desc)] out += [hdr] out += [''] @@ -316,14 +314,14 @@ class SphinxDocString(NumpyDocString): if len(idx) == 0: return out - out += ['.. index:: %s' % idx.get('default', '')] + out += [f".. index:: {idx.get('default', '')}"] for section, references in idx.items(): if section == 'default': continue elif section == 'refguide': - out += [' single: %s' % (', '.join(references))] + out += [f" single: {', '.join(references)}"] else: - out += [' %s: %s' % (section, ','.join(references))] + out += [f" {section}: {','.join(references)}"] out += [''] return out @@ -343,7 +341,7 @@ class SphinxDocString(NumpyDocString): m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) - out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] + out += [' ' + ", ".join([f"[{item}]_" for item in items]), ''] return out def _str_examples(self): diff --git a/numpydoc/numpydoc.py b/numpydoc/numpydoc.py index 5b11136..773079b 100644 --- a/numpydoc/numpydoc.py +++ b/numpydoc/numpydoc.py @@ -63,10 +63,10 @@ def rename_references(app, what, name, obj, options, lines): for r in references: new_r = prefix + '-' + r for i, line in enumerate(lines): - lines[i] = lines[i].replace('[%s]_' % r, - '[%s]_' % new_r) - lines[i] = lines[i].replace('.. [%s]' % r, - '.. [%s]' % new_r) + lines[i] = lines[i].replace(f'[{r}]_', + f'[{new_r}]_') + lines[i] = lines[i].replace(f'.. [{r}]', + f'.. [{new_r}]') def _is_cite_in_numpydoc_docstring(citation_node): @@ -119,10 +119,10 @@ def relabel_references(app, doc): # Sphinx has created pending_xref nodes with [reftext] text. def matching_pending_xref(node): return (isinstance(node, pending_xref) and - node[0].astext() == '[%s]' % ref_text) + node[0].astext() == f'[{ref_text}]') for xref_node in ref.parent.traverse(matching_pending_xref): - xref_node.replace(xref_node[0], Text('[%s]' % new_text)) + xref_node.replace(xref_node[0], Text(f'[{new_text}]')) ref.replace(ref_text, new_text.copy()) @@ -199,11 +199,11 @@ def mangle_docstrings(app, what, name, obj, options, lines): if (app.config.numpydoc_edit_link and hasattr(obj, '__name__') and obj.__name__): if hasattr(obj, '__module__'): - v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__)) + v = dict(full_name=f"{obj.__module__}.{obj.__name__}") else: v = dict(full_name=obj.__name__) lines += ['', '.. htmlonly::', ''] - lines += [' %s' % x for x in + lines += [f' {x}' for x in (app.config.numpydoc_edit_link % v).split("\n")] # call function to replace reference numbers so that there are no diff --git a/numpydoc/tests/test_validate.py b/numpydoc/tests/test_validate.py index ba56e2d..0e27dc8 100644 --- a/numpydoc/tests/test_validate.py +++ b/numpydoc/tests/test_validate.py @@ -1388,7 +1388,7 @@ class TestValidator: class TestValidatorClass: @pytest.mark.parametrize("invalid_name", ["unknown_mod", "unknown_mod.MyClass"]) def test_raises_for_invalid_module_name(self, invalid_name): - msg = 'No module can be imported from "{}"'.format(invalid_name) + msg = f'No module can be imported from "{invalid_name}"' with pytest.raises(ImportError, match=msg): numpydoc.validate.Validator._load_obj(invalid_name) @@ -1398,6 +1398,6 @@ class TestValidatorClass: def test_raises_for_invalid_attribute_name(self, invalid_name): name_components = invalid_name.split(".") obj_name, invalid_attr_name = name_components[-2], name_components[-1] - msg = "'{}' has no attribute '{}'".format(obj_name, invalid_attr_name) + msg = f"'{obj_name}' has no attribute '{invalid_attr_name}'" with pytest.raises(AttributeError, match=msg): numpydoc.validate.Validator._load_obj(invalid_name) diff --git a/numpydoc/validate.py b/numpydoc/validate.py index 3675737..b4b7e99 100644 --- a/numpydoc/validate.py +++ b/numpydoc/validate.py @@ -164,7 +164,7 @@ class Validator: else: break else: - raise ImportError("No module can be imported " 'from "{}"'.format(name)) + raise ImportError(f"No module can be imported from \"{name}\"") for part in func_parts: obj = getattr(obj, part) @@ -288,9 +288,9 @@ class Validator: Add stars to *args and **kwargs parameters """ if info.kind == inspect.Parameter.VAR_POSITIONAL: - return "*{}".format(param_name) + return f"*{param_name}" elif info.kind == inspect.Parameter.VAR_KEYWORD: - return "**{}".format(param_name) + return f"**{param_name}" else: return param_name @@ -420,7 +420,7 @@ def _check_desc(desc, code_no_desc, code_no_upper, code_no_period, **kwargs): # Find and strip out any sphinx directives desc = "\n".join(desc) for directive in DIRECTIVES: - full_directive = ".. {}".format(directive) + full_directive = f".. {directive}" if full_directive in desc: # Only retain any description before the directive desc = desc[: desc.index(full_directive)].rstrip("\n") diff --git a/numpydoc/xref.py b/numpydoc/xref.py index ee3954b..e3f507d 100644 --- a/numpydoc/xref.py +++ b/numpydoc/xref.py @@ -126,7 +126,7 @@ def make_xref(param_type, xref_aliases, xref_ignore): ignore_set = set() else: raise TypeError( - "xref_ignore must be a set or 'all', got {}".format(xref_ignore) + f"xref_ignore must be a set or 'all', got {xref_ignore}" ) if param_type in xref_aliases: @@ -137,9 +137,9 @@ def make_xref(param_type, xref_aliases, xref_ignore): if QUALIFIED_NAME_RE.match(link) and link not in ignore_set: if link != title: - return ':obj:`%s <%s>`' % (title, link) + return f':obj:`{title} <{link}>`' if wrap_unknown: - return ':obj:`%s`' % link + return f':obj:`{link}`' return link def _split_and_apply_re(s, pattern): -- cgit v1.2.1