Skip to content

Commit

Permalink
Use f-strings where possible
Browse files Browse the repository at this point in the history
  • Loading branch information
AA-Turner committed Apr 29, 2024
1 parent 7649798 commit ff81974
Show file tree
Hide file tree
Showing 74 changed files with 511 additions and 470 deletions.
6 changes: 4 additions & 2 deletions sphinx/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -1292,7 +1292,8 @@ def is_parallel_allowed(self, typ: str) -> bool:
"to check and make it explicit")
message_not_safe = __("the %s extension is not safe for parallel writing")
else:
raise ValueError('parallel type %s is not supported' % typ)
msg = f'parallel type {typ} is not supported'
raise ValueError(msg)

for ext in self.extensions.values():
allowed = getattr(ext, attrname, None)
Expand All @@ -1316,7 +1317,8 @@ def set_html_assets_policy(self, policy: Literal['always', 'per_page']) -> None:
.. versionadded: 4.1
"""
if policy not in ('always', 'per_page'):
raise ValueError('policy %s is not supported' % policy)
msg = f'policy {policy} is not supported'
raise ValueError(msg)
self.registry.html_assets_policy = policy


Expand Down
8 changes: 4 additions & 4 deletions sphinx/builders/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ def __init__(self, app: Sphinx, env: BuildEnvironment) -> None:
self.tags: Tags = app.tags
self.tags.add(self.format)
self.tags.add(self.name)
self.tags.add("format_%s" % self.format)
self.tags.add("builder_%s" % self.name)
self.tags.add(f'format_{self.format}')
self.tags.add(f'builder_{self.name}')

# images that need to be copied over (source -> dest)
self.images: dict[str, str] = {}
Expand Down Expand Up @@ -419,8 +419,8 @@ def read(self) -> list[str]:
self._read_serial(docnames)

if self.config.root_doc not in self.env.all_docs:
raise SphinxError('root file %s not found' %
self.env.doc2path(self.config.root_doc))
msg = f'root file {self.env.doc2path(self.config.root_doc)} not found'
raise SphinxError(msg)

for retval in self.events.emit('env-updated', self.env):
if retval is not None:
Expand Down
15 changes: 8 additions & 7 deletions sphinx/builders/changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,18 @@ def write(self, *ignored: Any) -> None:
with open(path.join(self.outdir, 'changes.html'), 'w', encoding='utf8') as f:
f.write(self.templates.render('changes/versionchanges.html', ctx))

hltext = ['.. versionadded:: %s' % version,
'.. versionchanged:: %s' % version,
'.. deprecated:: %s' % version,
'.. versionremoved:: %s' % version,
]
hltext = [
f'.. versionadded:: {version}',
f'.. versionchanged:: {version}',
f'.. deprecated:: {version}',
f'.. versionremoved:: {version}',
]

def hl(no: int, line: str) -> str:
line = '<a name="L%s"> </a>' % no + html.escape(line)
line = f'<a name="L{no}"> </a>{html.escape(line)}'
for x in hltext:
if x in line:
line = '<span class="hl">%s</span>' % line
line = f'<span class="hl">{line}</span>'
break
return line

Expand Down
5 changes: 2 additions & 3 deletions sphinx/builders/html/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,8 @@ def dump(self, f: IO) -> None:
f.write('# Sphinx build info version 1\n'
'# This file hashes the configuration used when building these files.'
' When it is not found, a full rebuild will be done.\n'
'config: %s\n'
'tags: %s\n' %
(self.config_hash, self.tags_hash))
f'config: {self.config_hash}\n'
f'tags: {self.tags_hash}\n')


class StandaloneHTMLBuilder(Builder):
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/latex/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def expand_show_urls(self) -> None:

self.expanded = True
else: # all other true values (b/w compat)
textnode = nodes.Text(" (%s)" % uri)
textnode = nodes.Text(f' ({uri})')
node.parent.insert(index + 1, textnode)

def get_docname_for_node(self, node: Node) -> str:
Expand Down
3 changes: 2 additions & 1 deletion sphinx/builders/linkcheck.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,8 @@ def process_result(self, result: CheckResult) -> None:
self.write_entry('redirected ' + text, result.docname, filename,
result.lineno, result.uri + ' to ' + result.message)
else:
raise ValueError('Unknown status %s.' % result.status)
msg = f'Unknown status {result.status}.'
raise ValueError(msg)

def write_linkstat(self, data: dict) -> None:
self.json_outfile.write(json.dumps(data))
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/manpage.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def write(self, *ignored: Any) -> None:
docsettings.section = section

if self.config.man_make_section_directory:
dirname = 'man%s' % section
dirname = f'man{section}'
ensuredir(path.join(self.outdir, dirname))
targetname = f'{dirname}/{name}.{section}'
else:
Expand Down
2 changes: 1 addition & 1 deletion sphinx/cmd/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def handle_exception(
print(red(__('reST markup error:')), file=stderr)
print(terminal_safe(exception.args[0]), file=stderr)
elif isinstance(exception, SphinxError):
print(red('%s:' % exception.category), file=stderr)
print(red(f'{exception.category}:'), file=stderr)
print(str(exception), file=stderr)
elif isinstance(exception, UnicodeError):
print(red(__('Encoding error:')), file=stderr)
Expand Down
28 changes: 16 additions & 12 deletions sphinx/cmd/make_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,15 @@ def build_clean(self) -> int:
if not path.exists(self.builddir):
return 0
elif not path.isdir(self.builddir):
print("Error: %r is not a directory!" % self.builddir)
print(f'Error: {self.builddir!r} is not a directory!')
return 1
elif srcdir == builddir:
print("Error: %r is same as source directory!" % self.builddir)
print(f'Error: {self.builddir!r} is same as source directory!')
return 1
elif path.commonpath([srcdir, builddir]) == builddir:
print("Error: %r directory contains source directory!" % self.builddir)
print(f'Error: {self.builddir!r} directory contains source directory!')
return 1
print("Removing everything under %r..." % self.builddir)
print(f'Removing everything under {self.builddir!r}...')
for item in os.listdir(self.builddir):
rmtree(self.builddir_join(item))
return 0
Expand All @@ -89,8 +89,9 @@ def build_help(self) -> None:
if not color_terminal():
nocolor()

print(bold("Sphinx v%s" % sphinx.__display_version__))
print("Please use `make %s' where %s is one of" % ((blue('target'),) * 2))
target = blue('target')
print(bold(f'Sphinx v{sphinx.__display_version__}'))
print(f"Please use `make {target}' where {target} is one of")
for osname, bname, description in BUILDERS:
if not osname or os.name == osname:
print(f' {blue(bname.ljust(10))} {description}')
Expand All @@ -103,12 +104,13 @@ def build_latexpdf(self) -> int:
make_fallback = 'make.bat' if sys.platform == 'win32' else 'make'
makecmd = os.environ.get('MAKE', make_fallback)
if not makecmd.lower().startswith('make'):
raise RuntimeError('Invalid $MAKE command: %r' % makecmd)
msg = f'Invalid $MAKE command: {makecmd!r}'
raise RuntimeError(msg)
try:
with chdir(self.builddir_join('latex')):
return subprocess.call([makecmd, 'all-pdf'])
except OSError:
print('Error: Failed to run: %s' % makecmd)
print(f'Error: Failed to run: {makecmd}')
return 1

def build_latexpdfja(self) -> int:
Expand All @@ -119,12 +121,13 @@ def build_latexpdfja(self) -> int:
make_fallback = 'make.bat' if sys.platform == 'win32' else 'make'
makecmd = os.environ.get('MAKE', make_fallback)
if not makecmd.lower().startswith('make'):
raise RuntimeError('Invalid $MAKE command: %r' % makecmd)
msg = f'Invalid $MAKE command: {makecmd!r}'
raise RuntimeError(msg)
try:
with chdir(self.builddir_join('latex')):
return subprocess.call([makecmd, 'all-pdf'])
except OSError:
print('Error: Failed to run: %s' % makecmd)
print(f'Error: Failed to run: {makecmd}')
return 1

def build_info(self) -> int:
Expand All @@ -134,12 +137,13 @@ def build_info(self) -> int:
# Use $MAKE to determine the make command
makecmd = os.environ.get('MAKE', 'make')
if not makecmd.lower().startswith('make'):
raise RuntimeError('Invalid $MAKE command: %r' % makecmd)
msg = f'Invalid $MAKE command: {makecmd!r}'
raise RuntimeError(msg)
try:
with chdir(self.builddir_join('texinfo')):
return subprocess.call([makecmd, 'info'])
except OSError:
print('Error: Failed to run: %s' % makecmd)
print(f'Error: Failed to run: {makecmd}')
return 1

def build_gettext(self) -> int:
Expand Down
6 changes: 3 additions & 3 deletions sphinx/cmd/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ def get_parser() -> argparse.ArgumentParser:
default=None,
help=__('quiet mode'))
parser.add_argument('--version', action='version', dest='show_version',
version='%%(prog)s %s' % __display_version__)
version=f'%(prog)s {__display_version__}')

parser.add_argument('path', metavar='PROJECT_DIR', default='.', nargs='?',
help=__('project root'))
Expand Down Expand Up @@ -511,8 +511,8 @@ def get_parser() -> argparse.ArgumentParser:

group = parser.add_argument_group(__('Extension options'))
for ext in EXTENSIONS:
group.add_argument('--ext-%s' % ext, action='append_const',
const='sphinx.ext.%s' % ext, dest='extensions',
group.add_argument(f'--ext-{ext}', action='append_const',
const=f'sphinx.ext.{ext}', dest='extensions',
help=__('enable %s extension') % ext)
group.add_argument('--extensions', metavar='EXTENSIONS', dest='extensions',
action='append', help=__('enable arbitrary extensions'))
Expand Down
2 changes: 1 addition & 1 deletion sphinx/directives/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ def run(self) -> list[Node]:
else:
literal_block = nodes.literal_block(self.block_text, self.block_text)
reporter = self.state.reporter
error = reporter.error('Unknown interpreted text role "%s".' % role_name,
error = reporter.error(f'Unknown interpreted text role "{role_name}".',
literal_block, line=self.lineno)
messages += [error]

Expand Down
12 changes: 8 additions & 4 deletions sphinx/directives/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,9 +320,11 @@ def start_filter(
return lines[lineno:]

if inclusive is True:
raise ValueError('start-after pattern not found: %s' % start)
msg = f'start-after pattern not found: {start}'
raise ValueError(msg)
else:
raise ValueError('start-at pattern not found: %s' % start)
msg = f'start-at pattern not found: {start}'
raise ValueError(msg)

return lines

Expand All @@ -349,9 +351,11 @@ def end_filter(
else:
return lines[:lineno]
if inclusive is True:
raise ValueError('end-at pattern not found: %s' % end)
msg = f'end-at pattern not found: {end}'
raise ValueError(msg)
else:
raise ValueError('end-before pattern not found: %s' % end)
msg = f'end-before pattern not found: {end}'
raise ValueError(msg)

return lines

Expand Down
4 changes: 2 additions & 2 deletions sphinx/directives/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def add_target(self, ret: list[Node]) -> None:
# assign label automatically if math_number_all enabled
if node['label'] == '' or (self.config.math_number_all and not node['label']):
seq = self.env.new_serialno('sphinx.ext.math#equations')
node['label'] = "%s:%d" % (self.env.docname, seq)
node['label'] = f'{self.env.docname}:{seq}'

# no targets and numbers are needed
if not node['label']:
Expand All @@ -170,7 +170,7 @@ def add_target(self, ret: list[Node]) -> None:
node['number'] = domain.get_equation_number_for(node['label'])

# add target node
node_id = make_id('equation-%s' % node['label'])
node_id = make_id(f'equation-{node["label"]}')
target = nodes.target('', '', ids=[node_id])
self.state.document.note_explicit_target(target)
ret.insert(0, target)
Expand Down
15 changes: 9 additions & 6 deletions sphinx/domains/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ class Index(ABC):

def __init__(self, domain: Domain) -> None:
if not self.name or self.localname is None:
raise SphinxError('Index subclass %s has no valid name or localname'
% self.__class__.__name__)
msg = f'Index subclass {self.__class__.__name__} has no valid name or localname'
raise SphinxError(msg)
self.domain = domain

@abstractmethod
Expand Down Expand Up @@ -223,7 +223,8 @@ def __init__(self, env: BuildEnvironment) -> None:
else:
self.data = env.domaindata[self.name]
if self.data['version'] != self.data_version:
raise OSError('data of %r domain out of date' % self.label)
msg = f'data of {self.label!r} domain out of date'
raise OSError(msg)
for name, obj in self.object_types.items():
for rolename in obj.roles:
self._role2type.setdefault(rolename, []).append(name)
Expand Down Expand Up @@ -300,9 +301,11 @@ def merge_domaindata(self, docnames: list[str], otherdata: dict[str, Any]) -> No
"""Merge in data regarding *docnames* from a different domaindata
inventory (coming from a subprocess in parallel builds).
"""
raise NotImplementedError('merge_domaindata must be implemented in %s '
'to be able to do parallel builds!' %
self.__class__)
msg = (
f'merge_domaindata must be implemented in {self.__class__} '
'to be able to do parallel builds!'
)
raise NotImplementedError(msg)

def process_doc(self, env: BuildEnvironment, docname: str,
document: nodes.document) -> None:
Expand Down
6 changes: 4 additions & 2 deletions sphinx/domains/c/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,10 @@ def handle_signature(self, sig: str, signode: TextElement) -> ASTDeclaration:
self.env.temp_data['c:last_symbol'] = e.symbol
msg = __("Duplicate C declaration, also defined at %s:%s.\n"
"Declaration is '.. c:%s:: %s'.")
msg = msg % (e.symbol.docname, e.symbol.line, self.display_object_type, sig)
logger.warning(msg, location=signode)
logger.warning(msg,
e.symbol.docname, e.symbol.line,
self.display_object_type, sig,
location=signode)

if ast.objectType == 'enumerator':
self._add_enumerator_to_parent(ast)
Expand Down
10 changes: 6 additions & 4 deletions sphinx/domains/c/_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ def describe_signature(self, signode: TextElement, mode: str, env: BuildEnvironm
elif mode == 'noneIsName':
signode += node
else:
raise Exception('Unknown description mode: %s' % mode)
msg = f'Unknown description mode: {mode}'
raise Exception(msg)

@property
def identifier(self) -> str:
Expand Down Expand Up @@ -183,7 +184,8 @@ def describe_signature(self, signode: TextElement, mode: str,
signode += dest
self.names[-1].describe_signature(signode, mode, env, '', symbol)
else:
raise Exception('Unknown description mode: %s' % mode)
msg = f'Unknown description mode: {mode}'
raise Exception(msg)


################################################################################
Expand Down Expand Up @@ -1365,8 +1367,8 @@ def __hash__(self) -> int:
return hash(self.exprs)

def _stringify(self, transform: StringifyTransform) -> str:
exprs = [transform(e) for e in self.exprs]
return '(%s)' % ', '.join(exprs)
exprs = ', '.join(map(transform, self.exprs))
return f'({exprs})'

def describe_signature(self, signode: TextElement, mode: str,
env: BuildEnvironment, symbol: Symbol) -> None:
Expand Down
Loading

0 comments on commit ff81974

Please sign in to comment.