From 814513ba9ffb1c0c1678b33757e263393b3c12d2 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 17 Nov 2019 17:04:34 +0100 Subject: [PATCH] Replace `a and b or c` by the more legible `b if a or c`. --- sphinx/application.py | 6 +++--- sphinx/builders/html.py | 11 ++++------- sphinx/builders/latex/__init__.py | 2 +- sphinx/cmd/quickstart.py | 10 +++++----- sphinx/directives/other.py | 2 +- sphinx/domains/javascript.py | 4 ++-- sphinx/domains/python.py | 6 +++--- sphinx/environment/adapters/toctree.py | 2 +- sphinx/ext/autodoc/__init__.py | 12 ++++++------ sphinx/ext/autosummary/__init__.py | 2 +- sphinx/ext/doctest.py | 6 +++--- sphinx/ext/intersphinx.py | 4 ++-- sphinx/ext/napoleon/docstring.py | 4 ++-- sphinx/jinja2glue.py | 2 +- sphinx/transforms/__init__.py | 2 +- sphinx/transforms/post_transforms/__init__.py | 2 +- sphinx/util/jsdump.py | 2 +- sphinx/writers/html.py | 2 +- sphinx/writers/html5.py | 2 +- sphinx/writers/latex.py | 4 ++-- sphinx/writers/texinfo.py | 6 +++--- 21 files changed, 45 insertions(+), 48 deletions(-) diff --git a/sphinx/application.py b/sphinx/application.py index a98e3a6a2..2284d6912 100644 --- a/sphinx/application.py +++ b/sphinx/application.py @@ -355,8 +355,8 @@ class Sphinx: if self._warncount and self.keep_going: self.statuscode = 1 - status = (self.statuscode == 0 and - __('succeeded') or __('finished with problems')) + status = (__('succeeded') if self.statuscode == 0 + else __('finished with problems')) if self._warncount: if self.warningiserror: msg = __('build %s, %s warning (with warnings treated as errors).', @@ -511,7 +511,7 @@ class Sphinx: logger.debug('[app] adding config value: %r', (name, default, rebuild) + ((types,) if types else ())) # type: ignore if rebuild in (False, True): - rebuild = rebuild and 'env' or '' + rebuild = 'env' if rebuild else '' self.config.add(name, default, rebuild, types) def add_event(self, name): diff --git a/sphinx/builders/html.py b/sphinx/builders/html.py index a0662dc82..20502f467 100644 --- a/sphinx/builders/html.py +++ b/sphinx/builders/html.py @@ -461,11 +461,8 @@ class StandaloneHTMLBuilder(Builder): else: self.last_updated = None - logo = self.config.html_logo and \ - path.basename(self.config.html_logo) or '' - - favicon = self.config.html_favicon and \ - path.basename(self.config.html_favicon) or '' + logo = path.basename(self.config.html_logo) if self.config.html_logo else '' + favicon = path.basename(self.config.html_favicon) if self.config.html_favicon else '' if not isinstance(self.config.html_use_opensearch, str): logger.warning(__('html_use_opensearch config value must now be a string')) @@ -567,7 +564,7 @@ class StandaloneHTMLBuilder(Builder): # title rendered as HTML title_node = self.env.longtitles.get(docname) - title = title_node and self.render_partial(title_node)['title'] or '' + title = self.render_partial(title_node)['title'] if title_node else '' # Suffix for the document source_suffix = path.splitext(self.env.doc2path(docname))[1] @@ -624,7 +621,7 @@ class StandaloneHTMLBuilder(Builder): self.imgpath = relative_uri(self.get_target_uri(docname), self.imagedir) self.post_process_images(doctree) title_node = self.env.longtitles.get(docname) - title = title_node and self.render_partial(title_node)['title'] or '' + title = self.render_partial(title_node)['title'] if title_node else '' self.index_page(docname, doctree, title) def finish(self) -> None: diff --git a/sphinx/builders/latex/__init__.py b/sphinx/builders/latex/__init__.py index de4223a0e..926e44a03 100644 --- a/sphinx/builders/latex/__init__.py +++ b/sphinx/builders/latex/__init__.py @@ -243,7 +243,7 @@ class LaTeXBuilder(Builder): doctree = self.assemble_doctree( docname, toctree_only, - appendices=((docclass != 'howto') and self.config.latex_appendices or [])) + appendices=(self.config.latex_appendices if docclass != 'howto' else [])) doctree['tocdepth'] = tocdepth self.post_process_images(doctree) self.update_doc_context(title, author) diff --git a/sphinx/cmd/quickstart.py b/sphinx/cmd/quickstart.py index 846750a68..95301897f 100644 --- a/sphinx/cmd/quickstart.py +++ b/sphinx/cmd/quickstart.py @@ -366,7 +366,7 @@ def generate(d: Dict, overwrite: bool = True, silent: bool = False, templatedir: ensuredir(d['path']) - srcdir = d['sep'] and path.join(d['path'], 'source') or d['path'] + srcdir = path.join(d['path'], 'source') if d['sep'] else d['path'] ensuredir(srcdir) if d['sep']: @@ -412,15 +412,15 @@ def generate(d: Dict, overwrite: bool = True, silent: bool = False, templatedir: batchfile_template = 'quickstart/make.bat_t' if d['makefile'] is True: - d['rsrcdir'] = d['sep'] and 'source' or '.' - d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build' + d['rsrcdir'] = 'source' if d['sep'] else '.' + d['rbuilddir'] = 'build' if d['sep'] else d['dot'] + 'build' # use binary mode, to avoid writing \r\n on Windows write_file(path.join(d['path'], 'Makefile'), template.render(makefile_template, d), '\n') if d['batchfile'] is True: - d['rsrcdir'] = d['sep'] and 'source' or '.' - d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build' + d['rsrcdir'] = 'source' if d['sep'] else '.' + d['rbuilddir'] = 'build' if d['sep'] else d['dot'] + 'build' write_file(path.join(d['path'], 'make.bat'), template.render(batchfile_template, d), '\r\n') diff --git a/sphinx/directives/other.py b/sphinx/directives/other.py index 1113e8241..a5a2831d6 100644 --- a/sphinx/directives/other.py +++ b/sphinx/directives/other.py @@ -300,7 +300,7 @@ class HList(SphinxDirective): index = 0 newnode = addnodes.hlist() for column in range(ncolumns): - endindex = index + (column < nmore and (npercol + 1) or npercol) + endindex = index + ((npercol + 1) if column < nmore else npercol) bullet_list = nodes.bullet_list() bullet_list += fulllist.children[index:endindex] newnode += addnodes.hlistcol('', bullet_list) diff --git a/sphinx/domains/javascript.py b/sphinx/domains/javascript.py index 121d5582d..da695065b 100644 --- a/sphinx/domains/javascript.py +++ b/sphinx/domains/javascript.py @@ -105,7 +105,7 @@ class JSObject(ObjectDescription): def add_target_and_index(self, name_obj: Tuple[str, str], sig: str, signode: desc_signature) -> None: mod_name = self.env.ref_context.get('js:module') - fullname = (mod_name and mod_name + '.' or '') + name_obj[0] + fullname = (mod_name + '.' if mod_name else '') + name_obj[0] if fullname not in self.state.document.ids: signode['names'].append(fullname) signode['ids'].append(fullname.replace('$', '_S_')) @@ -385,7 +385,7 @@ class JavaScriptDomain(Domain): ) -> Element: mod_name = node.get('js:module') prefix = node.get('js:object') - searchorder = node.hasattr('refspecific') and 1 or 0 + searchorder = 1 if node.hasattr('refspecific') else 0 name, obj = self.find_obj(env, mod_name, prefix, target, typ, searchorder) if not obj: return None diff --git a/sphinx/domains/python.py b/sphinx/domains/python.py index a2ed21f66..4374e0a71 100644 --- a/sphinx/domains/python.py +++ b/sphinx/domains/python.py @@ -315,7 +315,7 @@ class PyObject(ObjectDescription): def add_target_and_index(self, name_cls: Tuple[str, str], sig: str, signode: desc_signature) -> None: modname = self.options.get('module', self.env.ref_context.get('py:module')) - fullname = (modname and modname + '.' or '') + name_cls[0] + fullname = (modname + '.' if modname else '') + name_cls[0] # note target if fullname not in self.state.document.ids: signode['names'].append(fullname) @@ -830,7 +830,7 @@ class PythonModuleIndex(Index): num_toplevels += 1 subtype = 0 - qualifier = deprecated and _('Deprecated') or '' + qualifier = _('Deprecated') if deprecated else '' entries.append(IndexEntry(stripped + modname, subtype, docname, 'module-' + stripped + modname, platforms, qualifier, synopsis)) @@ -1008,7 +1008,7 @@ class PythonDomain(Domain): ) -> Element: modname = node.get('py:module') clsname = node.get('py:class') - searchmode = node.hasattr('refspecific') and 1 or 0 + searchmode = 1 if node.hasattr('refspecific') else 0 matches = self.find_obj(env, modname, clsname, target, type, searchmode) if not matches: diff --git a/sphinx/environment/adapters/toctree.py b/sphinx/environment/adapters/toctree.py index d5f827dde..0975b33cd 100644 --- a/sphinx/environment/adapters/toctree.py +++ b/sphinx/environment/adapters/toctree.py @@ -252,7 +252,7 @@ class TocTree: # prune the tree to maxdepth, also set toc depth and current classes _toctree_add_classes(newnode, 1) - self._toctree_prune(newnode, 1, prune and maxdepth or 0, collapse) + self._toctree_prune(newnode, 1, maxdepth if prune else 0, collapse) if isinstance(newnode[-1], nodes.Element) and len(newnode[-1]) == 0: # No titles found return None diff --git a/sphinx/ext/autodoc/__init__.py b/sphinx/ext/autodoc/__init__.py index d8e93727b..c053b5b75 100644 --- a/sphinx/ext/autodoc/__init__.py +++ b/sphinx/ext/autodoc/__init__.py @@ -295,7 +295,7 @@ class Documenter: # support explicit module and class name separation via :: if explicit_modname is not None: modname = explicit_modname[:-2] - parents = path and path.rstrip('.').split('.') or [] + parents = path.rstrip('.').split('.') if path else [] else: modname = None parents = [] @@ -308,7 +308,7 @@ class Documenter: self.args = args self.retann = retann self.fullname = (self.modname or '') + \ - (self.objpath and '.' + '.'.join(self.objpath) or '') + ('.' + '.'.join(self.objpath) if self.objpath else '') return True def import_object(self) -> bool: @@ -399,7 +399,7 @@ class Documenter: args, retann = result if args is not None: - return args + (retann and (' -> %s' % retann) or '') + return args + ((' -> %s' % retann) if retann else '') else: return '' @@ -1103,9 +1103,9 @@ class ClassDocumenter(DocstringSignatureMixin, ModuleLevelDocumenter): # type: sourcename = self.get_sourcename() self.add_line('', sourcename) if hasattr(self.object, '__bases__') and len(self.object.__bases__): - bases = [b.__module__ in ('__builtin__', 'builtins') and - ':class:`%s`' % b.__name__ or - ':class:`%s.%s`' % (b.__module__, b.__name__) + bases = [':class:`%s`' % b.__name__ + if b.__module__ in ('__builtin__', 'builtins') + else ':class:`%s.%s`' % (b.__module__, b.__name__) for b in self.object.__bases__] self.add_line(' ' + _('Bases: %s') % ', '.join(bases), sourcename) diff --git a/sphinx/ext/autosummary/__init__.py b/sphinx/ext/autosummary/__init__.py index de8c18baf..4530a4eff 100644 --- a/sphinx/ext/autosummary/__init__.py +++ b/sphinx/ext/autosummary/__init__.py @@ -722,7 +722,7 @@ def process_generate_options(app: Sphinx) -> None: if os.path.isfile(env.doc2path(x))] else: ext = list(app.config.source_suffix) - genfiles = [genfile + (not genfile.endswith(tuple(ext)) and ext[0] or '') + genfiles = [genfile + (ext[0] if not genfile.endswith(tuple(ext)) else '') for genfile in genfiles] for entry in genfiles[:]: diff --git a/sphinx/ext/doctest.py b/sphinx/ext/doctest.py index 996f8394f..1c356ff6d 100644 --- a/sphinx/ext/doctest.py +++ b/sphinx/ext/doctest.py @@ -326,7 +326,7 @@ class DocTestBuilder(Builder): def finish(self) -> None: # write executive summary def s(v: int) -> str: - return v != 1 and 's' or '' + return 's' if v != 1 else '' repl = (self.total_tries, s(self.total_tries), self.total_failures, s(self.total_failures), self.setup_failures, s(self.setup_failures), @@ -523,8 +523,8 @@ Doctest summary self.type = 'single' # as for ordinary doctests else: # testcode and output separate - output = code[1] and code[1].code or '' - options = code[1] and code[1].options or {} + output = code[1].code if code[1] else '' + options = code[1].options if code[1] else {} # disable processing as it is not needed options[doctest.DONT_ACCEPT_BLANKLINE] = True # find out if we're testing an exception diff --git a/sphinx/ext/intersphinx.py b/sphinx/ext/intersphinx.py index 7745d43d4..a403698f2 100644 --- a/sphinx/ext/intersphinx.py +++ b/sphinx/ext/intersphinx.py @@ -176,7 +176,7 @@ def fetch_inventory(app: Sphinx, uri: str, inv: Any) -> Any: uri = path.dirname(newinv) with f: try: - join = localuri and path.join or posixpath.join + join = path.join if localuri else posixpath.join invdata = InventoryFile.load(f, uri, join) except ValueError as exc: raise ValueError('unknown or unsupported inventory version: %r' % exc) @@ -401,7 +401,7 @@ def inspect_main(argv: List[str]) -> None: print(key) for entry, einfo in sorted(invdata[key].items()): print('\t%-40s %s%s' % (entry, - einfo[3] != '-' and '%-40s: ' % einfo[3] or '', + '%-40s: ' % einfo[3] if einfo[3] != '-' else '', einfo[2])) except ValueError as exc: print(exc.args[0] % exc.args[1:]) diff --git a/sphinx/ext/napoleon/docstring.py b/sphinx/ext/napoleon/docstring.py index 5610815bd..bb77aa22d 100644 --- a/sphinx/ext/napoleon/docstring.py +++ b/sphinx/ext/napoleon/docstring.py @@ -112,7 +112,7 @@ class GoogleDocstring: if not self._config: from sphinx.ext.napoleon import Config - self._config = self._app and self._app.config or Config() # type: ignore + self._config = self._app.config if self._app else Config() # type: ignore if not what: if inspect.isclass(obj): @@ -385,7 +385,7 @@ class GoogleDocstring: def _format_field(self, _name: str, _type: str, _desc: List[str]) -> List[str]: _desc = self._strip_empty(_desc) has_desc = any(_desc) - separator = has_desc and ' -- ' or '' + separator = ' -- ' if has_desc else '' if _name: if _type: if '`' in _type: diff --git a/sphinx/jinja2glue.py b/sphinx/jinja2glue.py index f767bd7f7..1a356c021 100644 --- a/sphinx/jinja2glue.py +++ b/sphinx/jinja2glue.py @@ -188,7 +188,7 @@ class BuiltinTemplateLoader(TemplateBridge, BaseLoader): self.loaders = [SphinxFileSystemLoader(x) for x in loaderchain] use_i18n = builder.app.translator is not None - extensions = use_i18n and ['jinja2.ext.i18n'] or [] + extensions = ['jinja2.ext.i18n'] if use_i18n else [] self.environment = SandboxedEnvironment(loader=self, extensions=extensions) self.environment.filters['tobool'] = _tobool diff --git a/sphinx/transforms/__init__.py b/sphinx/transforms/__init__.py index 3d72b88df..b6119d8da 100644 --- a/sphinx/transforms/__init__.py +++ b/sphinx/transforms/__init__.py @@ -296,7 +296,7 @@ class FilterSystemMessages(SphinxTransform): default_priority = 999 def apply(self, **kwargs) -> None: - filterlevel = self.config.keep_warnings and 2 or 5 + filterlevel = 2 if self.config.keep_warnings else 5 for node in self.document.traverse(nodes.system_message): if node['level'] < filterlevel: logger.debug('%s [filtered system message]', node.astext()) diff --git a/sphinx/transforms/post_transforms/__init__.py b/sphinx/transforms/post_transforms/__init__.py index 090ff0084..9cb7add44 100644 --- a/sphinx/transforms/post_transforms/__init__.py +++ b/sphinx/transforms/post_transforms/__init__.py @@ -155,7 +155,7 @@ class ReferencesResolver(SphinxPostTransform): if self.config.nitpicky: warn = True if self.config.nitpick_ignore: - dtype = domain and '%s:%s' % (domain.name, typ) or typ + dtype = '%s:%s' % (domain.name, typ) if domain else typ if (dtype, target) in self.config.nitpick_ignore: warn = False # for "std" types also try without domain name diff --git a/sphinx/util/jsdump.py b/sphinx/util/jsdump.py index bfdba170b..2be48a34a 100644 --- a/sphinx/util/jsdump.py +++ b/sphinx/util/jsdump.py @@ -83,7 +83,7 @@ def dumps(obj: Any, key: bool = False) -> str: if obj is None: return 'null' elif obj is True or obj is False: - return obj and 'true' or 'false' + return 'true' if obj else 'false' elif isinstance(obj, (int, float)): return str(obj) elif isinstance(obj, dict): diff --git a/sphinx/writers/html.py b/sphinx/writers/html.py index 11a9bbbc4..50816bcf6 100644 --- a/sphinx/writers/html.py +++ b/sphinx/writers/html.py @@ -90,7 +90,7 @@ class HTMLTranslator(SphinxTranslator, BaseTranslator): self.permalink_text = self.config.html_add_permalinks # support backwards-compatible setting to a bool if not isinstance(self.permalink_text, str): - self.permalink_text = self.permalink_text and '¶' or '' + self.permalink_text = '¶' if self.permalink_text else '' self.permalink_text = self.encode(self.permalink_text) self.secnumber_suffix = self.config.html_secnumber_suffix self.param_separator = '' diff --git a/sphinx/writers/html5.py b/sphinx/writers/html5.py index 5ace8572f..8eefab141 100644 --- a/sphinx/writers/html5.py +++ b/sphinx/writers/html5.py @@ -62,7 +62,7 @@ class HTML5Translator(SphinxTranslator, BaseTranslator): self.permalink_text = self.config.html_add_permalinks # support backwards-compatible setting to a bool if not isinstance(self.permalink_text, str): - self.permalink_text = self.permalink_text and '¶' or '' + self.permalink_text = '¶' if self.permalink_text else '' self.permalink_text = self.encode(self.permalink_text) self.secnumber_suffix = self.config.html_secnumber_suffix self.param_separator = '' diff --git a/sphinx/writers/latex.py b/sphinx/writers/latex.py index a3c676791..c52c1caf6 100644 --- a/sphinx/writers/latex.py +++ b/sphinx/writers/latex.py @@ -699,7 +699,7 @@ class LaTeXTranslator(SphinxTranslator): def hypertarget(self, id: str, withdoc: bool = True, anchor: bool = True) -> str: if withdoc: id = self.curfilestack[-1] + ':' + id - return (anchor and '\\phantomsection' or '') + \ + return ('\\phantomsection' if anchor else '') + \ '\\label{%s}' % self.idescape(id) def hypertarget_to(self, node: Element, anchor: bool = False) -> str: @@ -1525,7 +1525,7 @@ class LaTeXTranslator(SphinxTranslator): elif isinstance(node[0], nodes.image) and 'width' in node[0]: length = self.latex_image_length(node[0]['width']) self.body.append('\\begin{wrapfigure}{%s}{%s}\n\\centering' % - (node['align'] == 'right' and 'r' or 'l', length or '0pt')) + ('r' if node['align'] == 'right' else 'l', length or '0pt')) self.context.append('\\end{wrapfigure}\n') elif self.in_minipage: self.body.append('\n\\begin{center}') diff --git a/sphinx/writers/texinfo.py b/sphinx/writers/texinfo.py index 757519740..bb4c2e23c 100644 --- a/sphinx/writers/texinfo.py +++ b/sphinx/writers/texinfo.py @@ -242,7 +242,7 @@ class TexinfoTranslator(SphinxTranslator): title = self.settings.title # type: str if not title: title_node = self.document.next_node(nodes.title) - title = (title_node and title_node.astext()) or '' + title = title_node.astext() if title_node else '' elements['title'] = self.escape_id(title) or '' # filename if not elements['filename']: @@ -292,7 +292,7 @@ class TexinfoTranslator(SphinxTranslator): # each section is also a node for section in self.document.traverse(nodes.section): title = cast(nodes.TextElement, section.next_node(nodes.Titular)) - name = (title and title.astext()) or '' + name = title.astext() if title else '' section['node_name'] = add_node_name(name) def collect_node_menus(self) -> None: @@ -306,7 +306,7 @@ class TexinfoTranslator(SphinxTranslator): node_menus[node['node_name']] = entries # try to find a suitable "Top" node title = self.document.next_node(nodes.title) - top = (title and title.parent) or self.document + top = title.parent if title else self.document if not isinstance(top, (nodes.document, nodes.section)): top = self.document if top is not self.document: