Skip to content

Commit

Permalink
Python-3-only clean ups discovered by pyupgrade
Browse files Browse the repository at this point in the history
https://github.com/asottile/pyupgrade

> A tool to automatically upgrade syntax for newer versions of the
> language.

- Drop u str prefix
- Drop base object inheritance
- Drop args to super()
- Use set literals
- Use dict comprehension
- Use set comprehension
  • Loading branch information
jdufresne authored and tk0miya committed Mar 18, 2019
1 parent 33ba281 commit 22afc77
Show file tree
Hide file tree
Showing 30 changed files with 72 additions and 76 deletions.
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
epub_max_image_width = 0
epub_show_urls = 'inline'
epub_use_index = False
epub_guide = (('toc', 'contents.xhtml', u'Table of Contents'),)
epub_guide = (('toc', 'contents.xhtml', 'Table of Contents'),)
epub_description = 'Sphinx documentation generator system manual'

latex_documents = [('contents', 'sphinx.tex', 'Sphinx Documentation',
Expand Down
4 changes: 2 additions & 2 deletions sphinx/builders/changes.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@ def hl(no, line):
'text': text
}
f.write(self.templates.render('changes/rstsource.html', ctx))
themectx = dict(('theme_' + key, val) for (key, val) in
self.theme.get_options({}).items())
themectx = {'theme_' + key: val for (key, val) in
self.theme.get_options({}).items()}
copy_asset_file(path.join(package_dir, 'themes', 'default', 'static', 'default.css_t'),
self.outdir, context=themectx, renderer=self.templates)
copy_asset_file(path.join(package_dir, 'themes', 'basic', 'static', 'basic.css'),
Expand Down
2 changes: 1 addition & 1 deletion sphinx/builders/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def __init__(self, config=None, tags=None, config_categories=[]):
self.tags_hash = ''

if config:
values = dict((c.name, c.value) for c in config.filter(config_categories))
values = {c.name: c.value for c in config.filter(config_categories)}
self.config_hash = get_stable_hash(values)

if tags:
Expand Down
11 changes: 5 additions & 6 deletions sphinx/cmd/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,7 @@ def ask_user(d):
d['extensions'].append('sphinx.ext.%s' % name)

# Handle conflicting options
if set(['sphinx.ext.imgmath', 'sphinx.ext.mathjax']).issubset(
d['extensions']):
if {'sphinx.ext.imgmath', 'sphinx.ext.mathjax'}.issubset(d['extensions']):
print(__('Note: imgmath and mathjax cannot be enabled at the same '
'time. imgmath has been deselected.'))
d['extensions'].remove('sphinx.ext.imgmath')
Expand Down Expand Up @@ -469,7 +468,7 @@ def valid_dir(d):
if not path.isdir(dir):
return False

if set(['Makefile', 'make.bat']) & set(os.listdir(dir)):
if {'Makefile', 'make.bat'} & set(os.listdir(dir)):
return False

if d['sep']:
Expand Down Expand Up @@ -590,7 +589,7 @@ def main(argv=sys.argv[1:]):

d = vars(args)
# delete None or False value
d = dict((k, v) for k, v in d.items() if v is not None)
d = {k: v for k, v in d.items() if v is not None}

# handle use of CSV-style extension values
d.setdefault('extensions', [])
Expand All @@ -601,12 +600,12 @@ def main(argv=sys.argv[1:]):

try:
if 'quiet' in d:
if not set(['project', 'author']).issubset(d):
if not {'project', 'author'}.issubset(d):
print(__('''"quiet" is specified, but any of "project" or \
"author" is not specified.'''))
return 1

if set(['quiet', 'project', 'author']).issubset(d):
if {'quiet', 'project', 'author'}.issubset(d):
# quiet mode with all required params satisfied, use default
d.setdefault('version', '')
d.setdefault('release', d['version'])
Expand Down
2 changes: 1 addition & 1 deletion sphinx/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def deprecated_alias(modname, objects, warning):
sys.modules[modname] = _ModuleWrapper(module, modname, objects, warning) # type: ignore


class _ModuleWrapper(object):
class _ModuleWrapper:
def __init__(self, module, modname, objects, warning):
# type: (Any, str, Dict, Type[Warning]) -> None
self._module = module
Expand Down
4 changes: 2 additions & 2 deletions sphinx/domains/c.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,12 @@ class CObject(ObjectDescription):

# These C types aren't described anywhere, so don't try to create
# a cross-reference to them
stopwords = set((
stopwords = {
'const', 'void', 'char', 'wchar_t', 'int', 'short',
'long', 'float', 'double', 'unsigned', 'signed', 'FILE',
'clock_t', 'time_t', 'ptrdiff_t', 'size_t', 'ssize_t',
'struct', '_Bool',
))
}

def _parse_type(self, node, ctype):
# type: (nodes.Element, str) -> None
Expand Down
2 changes: 1 addition & 1 deletion sphinx/ext/apidoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
]

INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
PY_SUFFIXES = {'.py', '.pyx'}


def makename(package, module):
Expand Down
2 changes: 1 addition & 1 deletion sphinx/ext/autodoc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def members_set_option(arg):
"""Used to convert the :members: option to auto directives."""
if arg is None:
return ALL
return set(x.strip() for x in arg.split(','))
return {x.strip() for x in arg.split(',')}


SUPPRESS = object()
Expand Down
2 changes: 1 addition & 1 deletion sphinx/ext/ifconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def run(self):

def process_ifconfig_nodes(app, doctree, docname):
# type: (Sphinx, nodes.document, str) -> None
ns = dict((confval.name, confval.value) for confval in app.config)
ns = {confval.name: confval.value for confval in app.config}
ns.update(app.config.__dict__.copy())
ns['builder'] = app.builder.name
for node in doctree.traverse(ifconfig):
Expand Down
4 changes: 2 additions & 2 deletions sphinx/ext/intersphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,9 @@ def _get_safe_url(url):
else:
frags = list(parts)
if parts.port:
frags[1] = '{0}@{1}:{2}'.format(parts.username, parts.hostname, parts.port)
frags[1] = '{}@{}:{}'.format(parts.username, parts.hostname, parts.port)
else:
frags[1] = '{0}@{1}'.format(parts.username, parts.hostname)
frags[1] = '{}@{}'.format(parts.username, parts.hostname)

return urlunsplit(frags)

Expand Down
2 changes: 1 addition & 1 deletion sphinx/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ class SphinxFileInput(FileInput):
def __init__(self, *args, **kwargs):
# type: (Any, Any) -> None
kwargs['error_handler'] = 'sphinx'
super(SphinxFileInput, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)


class SphinxRSTFileInput(SphinxBaseFileInput):
Expand Down
2 changes: 1 addition & 1 deletion sphinx/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
EXCLUDE_PATHS = ['**/_sources', '.#*', '**/.#*', '*.lproj/**']


class Project(object):
class Project:
"""A project is source code set of Sphinx document."""

def __init__(self, srcdir, source_suffix):
Expand Down
9 changes: 4 additions & 5 deletions sphinx/search/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,9 @@ def load_terms(mapping):
rv = {}
for k, v in mapping.items():
if isinstance(v, int):
rv[k] = set([index2fn[v]])
rv[k] = {index2fn[v]}
else:
rv[k] = set(index2fn[i] for i in v)
rv[k] = {index2fn[i] for i in v}
return rv

self._mapping = load_terms(frozen['terms'])
Expand Down Expand Up @@ -381,12 +381,11 @@ def freeze(self):
"""Create a usable data structure for serializing."""
docnames, titles = zip(*sorted(self._titles.items()))
filenames = [self._filenames.get(docname) for docname in docnames]
fn2index = dict((f, i) for (i, f) in enumerate(docnames))
fn2index = {f: i for (i, f) in enumerate(docnames)}
terms, title_terms = self.get_terms(fn2index)

objects = self.get_objects(fn2index) # populates _objtypes
objtypes = dict((v, k[0] + ':' + k[1])
for (k, v) in self._objtypes.items())
objtypes = {v: k[0] + ':' + k[1] for (k, v) in self._objtypes.items()}
objnames = self._objnames
return dict(docnames=docnames, filenames=filenames, titles=titles, terms=terms,
objects=objects, objtypes=objtypes, objnames=objnames,
Expand Down
4 changes: 2 additions & 2 deletions sphinx/search/ja.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,14 +155,14 @@ def split(self, input):


class DefaultSplitter(BaseSplitter):
patterns_ = dict([(re.compile(pattern), value) for pattern, value in {
patterns_ = {re.compile(pattern): value for pattern, value in {
'[一二三四五六七八九十百千万億兆]': 'M',
'[一-龠々〆ヵヶ]': 'H',
'[ぁ-ん]': 'I',
'[ァ-ヴーア-ン゙ー]': 'K',
'[a-zA-Za-zA-Z]': 'A',
'[0-90-9]': 'N',
}.items()])
}.items()}
BIAS__ = -332
BC1__ = {'HH': 6, 'II': 2461, 'KH': 406, 'OH': -1378}
BC2__ = {'AA': -3267, 'AI': 2744, 'AN': -878, 'HH': -4070, 'HM': -1711,
Expand Down
4 changes: 2 additions & 2 deletions sphinx/testing/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ def __init__(self, buildername='html', srcdir=None,
self._saved_directives = directives._directives.copy() # type: ignore
self._saved_roles = roles._roles.copy() # type: ignore

self._saved_nodeclasses = set(v for v in dir(nodes.GenericNodeVisitor)
if v.startswith('visit_'))
self._saved_nodeclasses = {v for v in dir(nodes.GenericNodeVisitor)
if v.startswith('visit_')}

try:
super().__init__(srcdir, confdir, outdir, doctreedir,
Expand Down
4 changes: 2 additions & 2 deletions sphinx/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@

logger = logging.getLogger(__name__)

default_substitutions = set([
default_substitutions = {
'version',
'release',
'today',
])
}


class SphinxTransform(Transform):
Expand Down
2 changes: 1 addition & 1 deletion sphinx/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def add_file(self, docname, newfile):
while uniquename in self._existing:
i += 1
uniquename = '%s%s%s' % (base, i, ext)
self[newfile] = (set([docname]), uniquename)
self[newfile] = ({docname}, uniquename)
self._existing.add(uniquename)
return uniquename

Expand Down
2 changes: 1 addition & 1 deletion tests/test_application.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def test_extension_in_blacklist(app, status, warning):
@pytest.mark.filterwarnings('ignore:The config variable "source_parsers"')
@pytest.mark.filterwarnings('ignore:app.add_source_parser\\(\\) does not support suffix')
def test_add_source_parser(app, status, warning):
assert set(app.config.source_suffix) == set(['.rst', '.md', '.test'])
assert set(app.config.source_suffix) == {'.rst', '.md', '.test'}

# .rst; only in :confval:`source_suffix`
assert '.rst' not in app.registry.get_source_parsers()
Expand Down
4 changes: 2 additions & 2 deletions tests/test_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def test_incremental_reading(app):
# second reading
updated = app.builder.read()

assert set(updated) == set(['index', 'new'])
assert set(updated) == {'index', 'new'}
assert 'autodoc' not in app.env.all_docs
assert 'autodoc' not in app.env.found_docs

Expand All @@ -44,4 +44,4 @@ def test_incremental_reading_for_missing_files(app):

# "index" is listed up to updated because it contains references
# to nonexisting downloadable or image files
assert set(updated) == set(['index'])
assert set(updated) == {'index'}
10 changes: 5 additions & 5 deletions tests/test_catalogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ def test_compile_all_catalogs(app, status, warning):

locale_dir = app.srcdir / 'locale'
catalog_dir = locale_dir / app.config.language / 'LC_MESSAGES'
expect = set([
expect = {
x.replace('.po', '.mo')
for x in find_files(catalog_dir, '.po')
])
}
actual = set(find_files(catalog_dir, '.mo'))
assert actual # not empty
assert actual == expect
Expand All @@ -66,7 +66,7 @@ def get_actual():
actual_on_boot = get_actual() # sphinx.mo might be included
app.builder.compile_specific_catalogs([app.srcdir / 'admonitions.txt'])
actual = get_actual() - actual_on_boot
assert actual == set(['admonitions.mo'])
assert actual == {'admonitions.mo'}


@pytest.mark.usefixtures('setup_test')
Expand All @@ -79,10 +79,10 @@ def test_compile_update_catalogs(app, status, warning):

locale_dir = app.srcdir / 'locale'
catalog_dir = locale_dir / app.config.language / 'LC_MESSAGES'
expect = set([
expect = {
x.replace('.po', '.mo')
for x in find_files(catalog_dir, '.po')
])
}
actual = set(find_files(catalog_dir, '.mo'))
assert actual # not empty
assert actual == expect
13 changes: 6 additions & 7 deletions tests/test_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,20 @@ def test_images(app):
htmlbuilder.imgpath = 'dummy'
htmlbuilder.post_process_images(tree)
assert set(htmlbuilder.images.keys()) == \
set(['subdir/img.png', 'img.png', 'subdir/simg.png', 'svgimg.svg',
'img.foo.png'])
{'subdir/img.png', 'img.png', 'subdir/simg.png', 'svgimg.svg', 'img.foo.png'}
assert set(htmlbuilder.images.values()) == \
set(['img.png', 'img1.png', 'simg.png', 'svgimg.svg', 'img.foo.png'])
{'img.png', 'img1.png', 'simg.png', 'svgimg.svg', 'img.foo.png'}

latexbuilder = LaTeXBuilder(app)
latexbuilder.set_environment(app.env)
latexbuilder.init()
latexbuilder.post_process_images(tree)
assert set(latexbuilder.images.keys()) == \
set(['subdir/img.png', 'subdir/simg.png', 'img.png', 'img.pdf',
'svgimg.pdf', 'img.foo.png'])
{'subdir/img.png', 'subdir/simg.png', 'img.png', 'img.pdf',
'svgimg.pdf', 'img.foo.png'}
assert set(latexbuilder.images.values()) == \
set(['img.pdf', 'img.png', 'img1.png', 'simg.png',
'svgimg.pdf', 'img.foo.png'])
{'img.pdf', 'img.png', 'img1.png', 'simg.png',
'svgimg.pdf', 'img.foo.png'}


@pytest.mark.sphinx('dummy')
Expand Down
8 changes: 4 additions & 4 deletions tests/test_environment_toctree.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ def test_process_doc(app):
# other collections
assert app.env.toc_num_entries['index'] == 6
assert app.env.toctree_includes['index'] == ['foo', 'bar', 'baz']
assert app.env.files_to_rebuild['foo'] == set(['index'])
assert app.env.files_to_rebuild['bar'] == set(['index'])
assert app.env.files_to_rebuild['baz'] == set(['index'])
assert app.env.files_to_rebuild['foo'] == {'index'}
assert app.env.files_to_rebuild['bar'] == {'index'}
assert app.env.files_to_rebuild['baz'] == {'index'}
assert app.env.glob_toctrees == set()
assert app.env.numbered_toctrees == set(['index'])
assert app.env.numbered_toctrees == {'index'}

# qux has no section title
assert len(app.env.tocs['qux']) == 0
Expand Down
2 changes: 1 addition & 1 deletion tests/test_ext_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def test_build(app, status, warning):
undoc_py, undoc_c = pickle.loads((app.outdir / 'undoc.pickle').bytes())
assert len(undoc_c) == 1
# the key is the full path to the header file, which isn't testable
assert list(undoc_c.values())[0] == set([('function', 'Py_SphinxTest')])
assert list(undoc_c.values())[0] == {('function', 'Py_SphinxTest')}

assert 'autodoc_target' in undoc_py
assert 'funcs' in undoc_py['autodoc_target']
Expand Down
2 changes: 1 addition & 1 deletion tests/test_ext_inheritance_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def test_import_classes(rootdir):

# all of classes in the module
classes = import_classes('sphinx.application', None)
assert set(classes) == set([Sphinx, TemplateBridge])
assert set(classes) == {Sphinx, TemplateBridge}

# specified class in the module
classes = import_classes('sphinx.application.Sphinx', None)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_ext_napoleon_docstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class NamedtupleSubclass(namedtuple('NamedtupleSubclass', ('attr1', 'attr2'))):
__slots__ = ()

def __new__(cls, attr1, attr2=None):
return super(NamedtupleSubclass, cls).__new__(cls, attr1, attr2)
return super().__new__(cls, attr1, attr2)


class BaseDocstringTest(TestCase):
Expand Down
12 changes: 6 additions & 6 deletions tests/test_ext_todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@ def on_todo_defined(app, node):

# check handled event
assert len(todos) == 3
assert set(todo[1].astext() for todo in todos) == {'todo in foo',
'todo in bar',
'todo in param field'}
assert {todo[1].astext() for todo in todos} == {'todo in foo',
'todo in bar',
'todo in param field'}


@pytest.mark.sphinx('html', testroot='ext-todo', freshenv=True,
Expand Down Expand Up @@ -92,9 +92,9 @@ def on_todo_defined(app, node):

# check handled event
assert len(todos) == 3
assert set(todo[1].astext() for todo in todos) == {'todo in foo',
'todo in bar',
'todo in param field'}
assert {todo[1].astext() for todo in todos} == {'todo in foo',
'todo in bar',
'todo in param field'}


@pytest.mark.sphinx('latex', testroot='ext-todo', freshenv=True,
Expand Down
3 changes: 1 addition & 2 deletions tests/test_intl.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,8 +829,7 @@ def test_xml_footnote_backlinks(app):

para0 = secs[0].findall('paragraph')
refs0 = para0[0].findall('footnote_reference')
refid2id = dict([
(r.attrib.get('refid'), r.attrib.get('ids')) for r in refs0])
refid2id = {r.attrib.get('refid'): r.attrib.get('ids') for r in refs0}

footnote0 = secs[0].findall('footnote')
for footnote in footnote0:
Expand Down
Loading

0 comments on commit 22afc77

Please sign in to comment.