Skip to content

Use fstrings #353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@
"**": [],
}

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,
Expand Down
21 changes: 10 additions & 11 deletions numpydoc/docscrape.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -154,7 +154,7 @@ def __getitem__(self, key):

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

Expand Down Expand Up @@ -492,11 +492,11 @@ def _str_see_also(self, func_role):
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]
Expand All @@ -519,12 +519,12 @@ def _str_index(self):
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 ''
Expand Down Expand Up @@ -583,9 +583,8 @@ def __str__(self):

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
Expand All @@ -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:
Expand Down
24 changes: 11 additions & 13 deletions numpydoc/docscrape_sphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def _process_param(self, param, desc, fake_autosummary):
# 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
Expand All @@ -156,14 +156,12 @@ def _process_param(self, param, desc, fake_autosummary):

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]
Expand Down Expand Up @@ -239,11 +237,11 @@ def _str_member_list(self, name):
"""
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 = []
Expand All @@ -259,7 +257,7 @@ def _str_member_list(self, name):

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)

Expand All @@ -279,7 +277,7 @@ def _str_member_list(self, name):
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 += ['']
Expand Down Expand Up @@ -316,14 +314,14 @@ def _str_index(self):
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

Expand All @@ -343,7 +341,7 @@ def _str_references(self):
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):
Expand Down
16 changes: 8 additions & 8 deletions numpydoc/numpydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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())


Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions numpydoc/tests/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1388,7 +1388,7 @@ def test_bad_docstrings(self, capsys, klass, func, msgs):
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)

Expand All @@ -1398,6 +1398,6 @@ def test_raises_for_invalid_module_name(self, invalid_name):
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)
8 changes: 4 additions & 4 deletions numpydoc/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def _load_obj(name):
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)
Expand Down Expand Up @@ -288,9 +288,9 @@ def add_stars(param_name, info):
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

Expand Down Expand Up @@ -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")
Expand Down
6 changes: 3 additions & 3 deletions numpydoc/xref.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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):
Expand Down