Skip to content

Commit

Permalink
Run the pyupgrade tool
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner committed Oct 17, 2022
1 parent b277abc commit 920828f
Show file tree
Hide file tree
Showing 52 changed files with 119 additions and 129 deletions.
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def linkify_issues_in_changelog(app, docname, source):

def linkify(match):
url = 'https://github.com/sphinx-doc/sphinx/issues/' + match[1]
return '`{} <{}>`_'.format(match[0], url)
return f'`{match[0]} <{url}>`_'

linkified_changelog = re.sub(r'(?:PR)?#([0-9]+)\b', linkify, changelog)

Expand Down
4 changes: 2 additions & 2 deletions doc/development/tutorials/examples/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,8 @@ def resolve_xref(self, env, fromdocname, builder, typ, target, node,

def add_recipe(self, signature, ingredients):
"""Add a new recipe to the domain."""
name = '{}.{}'.format('recipe', signature)
anchor = 'recipe-{}'.format(signature)
name = f'recipe.{signature}'
anchor = f'recipe-{signature}'

self.data['recipe_ingredients'][name] = ingredients
# name, dispname, type, docname, anchor, priority
Expand Down
3 changes: 1 addition & 2 deletions doc/usage/extensions/example_google.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,7 @@ def example_generator(n):
[0, 1, 2, 3]
"""
for i in range(n):
yield i
yield from range(n)


class ExampleError(Exception):
Expand Down
3 changes: 1 addition & 2 deletions doc/usage/extensions/example_numpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,7 @@ def example_generator(n):
[0, 1, 2, 3]
"""
for i in range(n):
yield i
yield from range(n)


class ExampleError(Exception):
Expand Down
3 changes: 1 addition & 2 deletions sphinx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@
ret = subprocess.run(
['git', 'show', '-s', '--pretty=format:%h'],
cwd=package_dir,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
capture_output=True,
encoding='ascii',
).stdout
if ret:
Expand Down
2 changes: 1 addition & 1 deletion sphinx/addnodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ class desc_parameterlist(nodes.Part, nodes.Inline, nodes.FixedTextElement):
child_text_separator = ', '

def astext(self):
return '({})'.format(super().astext())
return f'({super().astext()})'


class desc_parameter(nodes.Part, nodes.Inline, nodes.FixedTextElement):
Expand Down
2 changes: 1 addition & 1 deletion sphinx/cmd/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ def write_file(fpath: str, content: str, newline: Optional[str] = None) -> None:
if overwrite or not path.isfile(fpath):
if 'quiet' not in d:
print(__('Creating file %s.') % fpath)
with open(fpath, 'wt', encoding='utf-8', newline=newline) as f:
with open(fpath, 'w', encoding='utf-8', newline=newline) as f:
f.write(content)
else:
if 'quiet' not in d:
Expand Down
2 changes: 1 addition & 1 deletion sphinx/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ def check_confval_types(app: Optional["Sphinx"], config: Config) -> None:
if annotations:
msg = __("The config value `{name}' has type `{current.__name__}'; "
"expected {permitted}.")
wrapped_annotations = ["`{}'".format(c.__name__) for c in annotations]
wrapped_annotations = [f"`{c.__name__}'" for c in annotations]
if len(wrapped_annotations) > 2:
permitted = "{}, or {}".format(
", ".join(wrapped_annotations[:-1]),
Expand Down
4 changes: 2 additions & 2 deletions sphinx/domains/c.py
Original file line number Diff line number Diff line change
Expand Up @@ -1826,7 +1826,7 @@ def _add_symbols(self, nestedName: ASTNestedName,
Symbol.debug_indent += 1
Symbol.debug_print("nn: ", nestedName)
Symbol.debug_print("decl: ", declaration)
Symbol.debug_print("location: {}:{}".format(docname, line))
Symbol.debug_print(f"location: {docname}:{line}")

def onMissingQualifiedSymbol(parentSymbol: "Symbol", ident: ASTIdentifier) -> "Symbol":
if Symbol.debug_lookup:
Expand All @@ -1852,7 +1852,7 @@ def onMissingQualifiedSymbol(parentSymbol: "Symbol", ident: ASTIdentifier) -> "S
Symbol.debug_indent += 1
Symbol.debug_print("ident: ", lookupResult.ident)
Symbol.debug_print("declaration: ", declaration)
Symbol.debug_print("location: {}:{}".format(docname, line))
Symbol.debug_print(f"location: {docname}:{line}")
Symbol.debug_indent -= 1
symbol = Symbol(parent=lookupResult.parentSymbol,
ident=lookupResult.ident,
Expand Down
34 changes: 17 additions & 17 deletions sphinx/domains/cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,7 @@ def _stringify(self, transform: StringifyTransform) -> str:

def get_id(self, version: int) -> str:
# mangle as if it was a function call: ident(literal)
return 'clL_Zli{}E{}E'.format(self.ident.get_id(version), self.literal.get_id(version))
return f'clL_Zli{self.ident.get_id(version)}E{self.literal.get_id(version)}E'

def describe_signature(self, signode: TextElement, mode: str,
env: "BuildEnvironment", symbol: "Symbol") -> None:
Expand Down Expand Up @@ -4635,7 +4635,7 @@ def _add_symbols(self, nestedName: ASTNestedName, templateDecls: List[Any],
Symbol.debug_print("tdecls:", ",".join(str(t) for t in templateDecls))
Symbol.debug_print("nn: ", nestedName)
Symbol.debug_print("decl: ", declaration)
Symbol.debug_print("location: {}:{}".format(docname, line))
Symbol.debug_print(f"location: {docname}:{line}")

def onMissingQualifiedSymbol(parentSymbol: "Symbol",
identOrOp: Union[ASTIdentifier, ASTOperator],
Expand Down Expand Up @@ -4673,7 +4673,7 @@ def onMissingQualifiedSymbol(parentSymbol: "Symbol",
Symbol.debug_print("identOrOp: ", lookupResult.identOrOp)
Symbol.debug_print("templateArgs: ", lookupResult.templateArgs)
Symbol.debug_print("declaration: ", declaration)
Symbol.debug_print("location: {}:{}".format(docname, line))
Symbol.debug_print(f"location: {docname}:{line}")
Symbol.debug_indent -= 1
symbol = Symbol(parent=lookupResult.parentSymbol,
identOrOp=lookupResult.identOrOp,
Expand Down Expand Up @@ -6025,23 +6025,23 @@ def _parse_simple_type_specifiers(self) -> ASTTrailingTypeSpecFundamental:
'float', 'double',
'__float80', '_Float64x', '__float128', '_Float128'):
if typ is not None:
self.fail("Can not have both {} and {}.".format(t, typ))
self.fail(f"Can not have both {t} and {typ}.")
typ = t
elif t in ('signed', 'unsigned'):
if signedness is not None:
self.fail("Can not have both {} and {}.".format(t, signedness))
self.fail(f"Can not have both {t} and {signedness}.")
signedness = t
elif t == 'short':
if len(width) != 0:
self.fail("Can not have both {} and {}.".format(t, width[0]))
self.fail(f"Can not have both {t} and {width[0]}.")
width.append(t)
elif t == 'long':
if len(width) != 0 and width[0] != 'long':
self.fail("Can not have both {} and {}.".format(t, width[0]))
self.fail(f"Can not have both {t} and {width[0]}.")
width.append(t)
elif t in ('_Imaginary', '_Complex'):
if modifier is not None:
self.fail("Can not have both {} and {}.".format(t, modifier))
self.fail(f"Can not have both {t} and {modifier}.")
modifier = t
self.skip_ws()
if len(names) == 0:
Expand All @@ -6051,41 +6051,41 @@ def _parse_simple_type_specifiers(self) -> ASTTrailingTypeSpecFundamental:
'wchar_t', 'char8_t', 'char16_t', 'char32_t',
'__float80', '_Float64x', '__float128', '_Float128'):
if modifier is not None:
self.fail("Can not have both {} and {}.".format(typ, modifier))
self.fail(f"Can not have both {typ} and {modifier}.")
if signedness is not None:
self.fail("Can not have both {} and {}.".format(typ, signedness))
self.fail(f"Can not have both {typ} and {signedness}.")
if len(width) != 0:
self.fail("Can not have both {} and {}.".format(typ, ' '.join(width)))
elif typ == 'char':
if modifier is not None:
self.fail("Can not have both {} and {}.".format(typ, modifier))
self.fail(f"Can not have both {typ} and {modifier}.")
if len(width) != 0:
self.fail("Can not have both {} and {}.".format(typ, ' '.join(width)))
elif typ == 'int':
if modifier is not None:
self.fail("Can not have both {} and {}.".format(typ, modifier))
self.fail(f"Can not have both {typ} and {modifier}.")
elif typ in ('__int64', '__int128'):
if modifier is not None:
self.fail("Can not have both {} and {}.".format(typ, modifier))
self.fail(f"Can not have both {typ} and {modifier}.")
if len(width) != 0:
self.fail("Can not have both {} and {}.".format(typ, ' '.join(width)))
elif typ == 'float':
if signedness is not None:
self.fail("Can not have both {} and {}.".format(typ, signedness))
self.fail(f"Can not have both {typ} and {signedness}.")
if len(width) != 0:
self.fail("Can not have both {} and {}.".format(typ, ' '.join(width)))
elif typ == 'double':
if signedness is not None:
self.fail("Can not have both {} and {}.".format(typ, signedness))
self.fail(f"Can not have both {typ} and {signedness}.")
if len(width) > 1:
self.fail("Can not have both {} and {}.".format(typ, ' '.join(width)))
if len(width) == 1 and width[0] != 'long':
self.fail("Can not have both {} and {}.".format(typ, ' '.join(width)))
elif typ is None:
if modifier is not None:
self.fail("Can not have {} without a floating point type.".format(modifier))
self.fail(f"Can not have {modifier} without a floating point type.")
else:
raise AssertionError("Unhandled type {}".format(typ))
raise AssertionError(f"Unhandled type {typ}")

canonNames: List[str] = []
if modifier is not None:
Expand Down
3 changes: 2 additions & 1 deletion sphinx/environment/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@

if TYPE_CHECKING:
from collections.abc import MutableMapping
from typing import Literal

from typing_extensions import Literal, overload
from typing_extensions import overload

from sphinx.domains.c import CDomain
from sphinx.domains.changeset import ChangeSetDomain
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/graphviz.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import re
import subprocess
from os import path
from subprocess import PIPE, CalledProcessError
from subprocess import CalledProcessError
from typing import Any, Dict, List, Optional, Tuple

from docutils import nodes
Expand Down Expand Up @@ -244,7 +244,7 @@ def render_dot(self: SphinxTranslator, code: str, options: Dict, format: str,
dot_args.extend(['-Tcmapx', '-o%s.map' % outfn])

try:
ret = subprocess.run(dot_args, input=code.encode(), stdout=PIPE, stderr=PIPE,
ret = subprocess.run(dot_args, input=code.encode(), capture_output=True,
cwd=cwd, check=True)
if not path.isfile(outfn):
raise GraphvizError(__('dot did not produce an output file:\n[stderr]\n%r\n'
Expand Down
6 changes: 3 additions & 3 deletions sphinx/ext/imgconverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import subprocess
import sys
from subprocess import PIPE, CalledProcessError
from subprocess import CalledProcessError
from typing import Any, Dict

import sphinx
Expand All @@ -28,7 +28,7 @@ def is_available(self) -> bool:
try:
args = [self.config.image_converter, '-version']
logger.debug('Invoking %r ...', args)
subprocess.run(args, stdout=PIPE, stderr=PIPE, check=True)
subprocess.run(args, capture_output=True, check=True)
return True
except OSError as exc:
logger.warning(__(
Expand Down Expand Up @@ -56,7 +56,7 @@ def convert(self, _from: str, _to: str) -> bool:
self.config.image_converter_args +
[_from, _to])
logger.debug('Invoking %r ...', args)
subprocess.run(args, stdout=PIPE, stderr=PIPE, check=True)
subprocess.run(args, capture_output=True, check=True)
return True
except OSError:
logger.warning(__('convert command %r cannot be run, '
Expand Down
6 changes: 3 additions & 3 deletions sphinx/ext/imgmath.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import subprocess
import tempfile
from os import path
from subprocess import PIPE, CalledProcessError
from subprocess import CalledProcessError
from typing import Any, Dict, List, Optional, Tuple

from docutils import nodes
Expand Down Expand Up @@ -130,7 +130,7 @@ def compile_math(latex: str, builder: Builder) -> str:
command.append('math.tex')

try:
subprocess.run(command, stdout=PIPE, stderr=PIPE, cwd=tempdir, check=True,
subprocess.run(command, capture_output=True, cwd=tempdir, check=True,
encoding='ascii')
return path.join(tempdir, 'math.dvi')
except OSError as exc:
Expand All @@ -145,7 +145,7 @@ def compile_math(latex: str, builder: Builder) -> str:
def convert_dvi_to_image(command: List[str], name: str) -> Tuple[str, str]:
"""Convert DVI file to specific image format."""
try:
ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True, encoding='ascii')
ret = subprocess.run(command, capture_output=True, check=True, encoding='ascii')
return ret.stdout, ret.stderr
except OSError as exc:
logger.warning(__('%s command %r cannot be run (needed for math '
Expand Down
6 changes: 3 additions & 3 deletions sphinx/ext/intersphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,9 @@ def _get_safe_url(url: str) -> str:
else:
frags = list(parts)
if parts.port:
frags[1] = '{}@{}:{}'.format(parts.username, parts.hostname, parts.port)
frags[1] = f'{parts.username}@{parts.hostname}:{parts.port}'
else:
frags[1] = '{}@{}'.format(parts.username, parts.hostname)
frags[1] = f'{parts.username}@{parts.hostname}'

return urlunsplit(frags)

Expand Down Expand Up @@ -334,7 +334,7 @@ def _resolve_reference_in_domain(env: BuildEnvironment,
objtypes.append('method')

# the inventory contains domain:type as objtype
objtypes = ["{}:{}".format(domain.name, t) for t in objtypes]
objtypes = [f"{domain.name}:{t}" for t in objtypes]

# now that the objtypes list is complete we can remove the disabled ones
if honor_disabled_refs:
Expand Down
2 changes: 1 addition & 1 deletion sphinx/ext/viewcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def should_generate_module_page(app: Sphinx, modname: str) -> bool:
if path.getmtime(module_filename) <= path.getmtime(page_filename):
# generation is not needed if the HTML page is newer than module file.
return False
except IOError:
except OSError:
pass

return True
Expand Down
2 changes: 1 addition & 1 deletion sphinx/pycode/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self, code: str = '') -> None:
def _visit_op(self, node: ast.AST) -> str:
return OPERATORS[node.__class__]
for _op in OPERATORS:
locals()['visit_{}'.format(_op.__name__)] = _visit_op
locals()[f'visit_{_op.__name__}'] = _visit_op

def visit_arg(self, node: ast.arg) -> str:
if node.annotation:
Expand Down
3 changes: 1 addition & 2 deletions sphinx/testing/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import sys
from collections import namedtuple
from io import StringIO
from subprocess import PIPE
from typing import Any, Callable, Dict, Generator, Optional, Tuple

import pytest
Expand Down Expand Up @@ -205,7 +204,7 @@ def if_graphviz_found(app: SphinxTestApp) -> None:
graphviz_dot = getattr(app.config, 'graphviz_dot', '')
try:
if graphviz_dot:
subprocess.run([graphviz_dot, '-V'], stdout=PIPE, stderr=PIPE) # show version
subprocess.run([graphviz_dot, '-V'], capture_output=True) # show version
return
except OSError: # No such file or directory
pass
Expand Down
2 changes: 1 addition & 1 deletion sphinx/util/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def get_full_module_name(node: Node) -> str:
:param nodes.Node node: target node
:return: full module dotted path
"""
return '{}.{}'.format(node.__module__, node.__class__.__name__)
return f'{node.__module__}.{node.__class__.__name__}'


def repr_domxml(node: Node, length: int = 80) -> str:
Expand Down
10 changes: 5 additions & 5 deletions sphinx/writers/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -1528,20 +1528,20 @@ def style(string: str) -> str:
try:
if type == 'single':
try:
p1, p2 = [escape(x) for x in split_into(2, 'single', string)]
p1, p2 = (escape(x) for x in split_into(2, 'single', string))
P1, P2 = style(p1), style(p2)
self.body.append(r'\index{%s@%s!%s@%s%s}' % (p1, P1, p2, P2, m))
except ValueError:
p = escape(split_into(1, 'single', string)[0])
P = style(p)
self.body.append(r'\index{%s@%s%s}' % (p, P, m))
elif type == 'pair':
p1, p2 = [escape(x) for x in split_into(2, 'pair', string)]
p1, p2 = (escape(x) for x in split_into(2, 'pair', string))
P1, P2 = style(p1), style(p2)
self.body.append(r'\index{%s@%s!%s@%s%s}\index{%s@%s!%s@%s%s}' %
(p1, P1, p2, P2, m, p2, P2, p1, P1, m))
elif type == 'triple':
p1, p2, p3 = [escape(x) for x in split_into(3, 'triple', string)]
p1, p2, p3 = (escape(x) for x in split_into(3, 'triple', string))
P1, P2, P3 = style(p1), style(p2), style(p3)
self.body.append(
r'\index{%s@%s!%s %s@%s %s%s}'
Expand All @@ -1551,11 +1551,11 @@ def style(string: str) -> str:
p2, P2, p3, p1, P3, P1, m,
p3, P3, p1, p2, P1, P2, m))
elif type == 'see':
p1, p2 = [escape(x) for x in split_into(2, 'see', string)]
p1, p2 = (escape(x) for x in split_into(2, 'see', string))
P1 = style(p1)
self.body.append(r'\index{%s@%s|see{%s}}' % (p1, P1, p2))
elif type == 'seealso':
p1, p2 = [escape(x) for x in split_into(2, 'seealso', string)]
p1, p2 = (escape(x) for x in split_into(2, 'seealso', string))
P1 = style(p1)
self.body.append(r'\index{%s@%s|see{%s}}' % (p1, P1, p2))
else:
Expand Down

0 comments on commit 920828f

Please sign in to comment.