Skip to content
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

MNT: Remove Python 2 leftovers #1116

Merged
merged 2 commits into from
Mar 30, 2023
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: 0 additions & 2 deletions bin/sphx_glr_python_to_jupyter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
Sphinx Gallery Notebook converter
=================================
Expand All @@ -11,7 +10,6 @@
# Author: Óscar Nájera
# License: 3-clause BSD

from __future__ import division, absolute_import, print_function

from sphinx_gallery.notebook import python_to_jupyter_cli

Expand Down
19 changes: 9 additions & 10 deletions doc/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Sphinx-Gallery documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 17 16:01:26 2014.
Expand Down Expand Up @@ -65,8 +64,8 @@
master_doc = 'index'

# General information about the project.
project = u'Sphinx-Gallery'
copyright = u'2014-%s, Sphinx-gallery developers' % date.today().year
project = 'Sphinx-Gallery'
copyright = '2014-%s, Sphinx-gallery developers' % date.today().year

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -257,8 +256,8 @@ def setup(app):
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'Sphinx-Gallery.tex', u'Sphinx-Gallery Documentation',
u'Óscar Nájera', 'manual'),
('index', 'Sphinx-Gallery.tex', 'Sphinx-Gallery Documentation',
'Óscar Nájera', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
Expand Down Expand Up @@ -287,8 +286,8 @@ def setup(app):
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'sphinx-gallery', u'Sphinx-Gallery Documentation',
[u'Óscar Nájera'], 1)
('index', 'sphinx-gallery', 'Sphinx-Gallery Documentation',
['Óscar Nájera'], 1)
]

# If true, show URL addresses after external links.
Expand All @@ -301,8 +300,8 @@ def setup(app):
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Sphinx-Gallery', u'Sphinx-Gallery Documentation',
u'Óscar Nájera', 'Sphinx-Gallery', 'One line description of project.',
('index', 'Sphinx-Gallery', 'Sphinx-Gallery Documentation',
'Óscar Nájera', 'Sphinx-Gallery', 'One line description of project.',
'Miscellaneous'),
]

Expand All @@ -321,7 +320,7 @@ def setup(app):

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('https://docs.python.org/{.major}'.format(sys.version_info), None),
'python': (f'https://docs.python.org/{sys.version_info.major}', None),
'numpy': ('https://numpy.org/doc/stable/', None),
'matplotlib': ('https://matplotlib.org/stable', None),
'pyvista': ('https://docs.pyvista.org/', None),
Expand Down
2 changes: 0 additions & 2 deletions examples/no_output/just_code.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
A short Python script
=====================
Expand All @@ -10,5 +9,4 @@

# Code source: Óscar Nájera
# License: BSD 3 clause
from __future__ import print_function
print([i for i in range(10)])
1 change: 0 additions & 1 deletion examples/no_output/plot_raise.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Example that fails to execute
=============================
Expand Down
1 change: 0 additions & 1 deletion examples/no_output/plot_strings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Constrained Text output frame
=============================
Expand Down
1 change: 0 additions & 1 deletion examples/no_output/plot_syntaxerror.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Example with SyntaxError
========================
Expand Down
1 change: 0 additions & 1 deletion examples/plot_0_sin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Introductory example - Plotting sin
===================================
Expand Down
5 changes: 2 additions & 3 deletions examples/plot_1_exp.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Plotting the exponential function
=================================
Expand Down Expand Up @@ -28,13 +27,13 @@ def main():
plt.figure()
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$\exp(x)$')
plt.ylabel(r'$\exp(x)$')
plt.title('Exponential function')

plt.figure()
plt.plot(x, -np.exp(-x))
plt.xlabel('$x$')
plt.ylabel('$-\exp(-x)$')
plt.ylabel(r'$-\exp(-x)$')
plt.title('Negative exponential\nfunction')
# To avoid matplotlib text output
plt.show()
Expand Down
2 changes: 0 additions & 2 deletions examples/plot_2_seaborn.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""
Seaborn example
===============
Expand All @@ -10,7 +9,6 @@
# Author: Michael Waskom & Lucy Liu
# License: BSD 3 clause

from __future__ import division, absolute_import, print_function


import numpy as np
Expand Down
1 change: 0 additions & 1 deletion examples/plot_3_capture_repr.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
.. _capture_repr_examples:

Expand Down
5 changes: 2 additions & 3 deletions examples/plot_4_choose_thumbnail.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Choosing the thumbnail figure
=============================
Expand All @@ -25,15 +24,15 @@ def main():
plt.figure()
plt.plot(x, y)
plt.xlabel('$x$')
plt.ylabel('$\exp(x)$')
plt.ylabel(r'$\exp(x)$')

# The next line sets the thumbnail for the second figure in the gallery
# (plot with negative exponential in orange)
# sphinx_gallery_thumbnail_number = 2
plt.figure()
plt.plot(x, -np.exp(-x), color='orange', linewidth=4)
plt.xlabel('$x$')
plt.ylabel('$-\exp(-x)$')
plt.ylabel(r'$-\exp(-x)$')
# To avoid matplotlib text output
plt.show()

Expand Down
1 change: 0 additions & 1 deletion examples/plot_4b_provide_thumbnail.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Providing a figure for the thumbnail image
==========================================
Expand Down
2 changes: 0 additions & 2 deletions examples/plot_5_unicode_everywhere.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
"""
Using Unicode everywhere 🤗
===========================

This example demonstrates how to include non-ASCII characters, mostly emoji 🎉
to stress test the build and test environments that parse the example files.
"""
from __future__ import unicode_literals

# 🎉 👍
# Code source: Óscar Nájera
Expand Down
1 change: 0 additions & 1 deletion examples/plot_6_function_identifier.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Identifying function names in a script
======================================
Expand Down
3 changes: 1 addition & 2 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Author: Óscar Nájera
# License: 3-clause BSD
"""
Expand Down Expand Up @@ -28,7 +27,7 @@
description = description.strip()

# Get the requirements from requirements.txt and environment
with open('requirements.txt', 'r') as fid:
with open('requirements.txt') as fid:
install_requires = [line.strip() for line in fid if line.strip()]

setup(
Expand Down
10 changes: 4 additions & 6 deletions sphinx_gallery/backreferences.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Author: Óscar Nájera
# License: 3-clause BSD
"""
Expand All @@ -7,7 +6,6 @@

Parses example file code in order to keep track of used functions
"""
from __future__ import print_function, unicode_literals

import ast
import codecs
Expand Down Expand Up @@ -40,7 +38,7 @@
"""


class DummyClass(object):
class DummyClass:
"""Dummy class for testing method resolution."""

def run(self):
Expand All @@ -60,7 +58,7 @@ class NameFinder(ast.NodeVisitor):
"""

def __init__(self, global_variables=None):
super(NameFinder, self).__init__()
super().__init__()
self.imported_names = {}
self.global_variables = global_variables or {}
self.accessed_names = set()
Expand Down Expand Up @@ -165,7 +163,7 @@ def get_mapping(self):


def _from_import(a, b):
imp_line = 'from %s import %s' % (a, b)
imp_line = f'from {a} import {b}'
scope = dict()
with warnings.catch_warnings(record=True): # swallow warnings
warnings.simplefilter('ignore')
Expand Down Expand Up @@ -355,6 +353,6 @@ def _finalize_backreferences(seen_backrefs, gallery_conf):
level = gallery_conf['log_level'].get('backreference_missing',
'warning')
func = getattr(logger, level)
func('Could not find backreferences file: %s' % (path,))
func(f'Could not find backreferences file: {path}')
func('The backreferences are likely to be erroneous '
'due to file system case insensitivity.')
10 changes: 5 additions & 5 deletions sphinx_gallery/directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def run(self):
heading = self.options['add-heading']
if heading == "":
if len(obj_list) == 1:
heading = 'Examples using ``{}``'.format(obj_list[0])
heading = f'Examples using ``{obj_list[0]}``'
else:
heading = 'Examples using one of multiple objects'
lines.append(heading)
Expand All @@ -66,7 +66,7 @@ def run(self):
def has_backrefs(obj):
src_dir = config.sphinx_gallery_conf['src_dir']
path = os.path.join(src_dir, backreferences_dir,
'{}.examples'.format(obj))
f'{obj}.examples')
return os.path.isfile(path) and os.path.getsize(path) > 0

if not any(has_backrefs(obj) for obj in obj_list):
Expand All @@ -78,7 +78,7 @@ def has_backrefs(obj):
for obj in obj_list:
path = os.path.join('/', # Sphinx treats this as the source dir
backreferences_dir,
'{}.examples'.format(obj))
f'{obj}.examples')

# Always remove the heading from the file
lines.append("""\
Expand Down Expand Up @@ -111,8 +111,8 @@ def directive_boolean(value):
elif value.lower().strip() in ['no', '0', 0, 'false', 'none']:
return False
else:
raise ValueError(u"Please use one of: yes, true, no, false. "
u"Do not use `{}` as boolean.".format(value))
raise ValueError("Please use one of: yes, true, no, false. "
"Do not use `{}` as boolean.".format(value))


class ImageSg(images.Image):
Expand Down
17 changes: 8 additions & 9 deletions sphinx_gallery/docs_resolv.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Author: Óscar Nájera
# License: 3-clause BSD
"""
Expand Down Expand Up @@ -39,7 +38,7 @@ def _get_data(url):
if encoding == 'gzip':
data = gzip.GzipFile(fileobj=BytesIO(data)).read()
elif encoding != 'plain':
raise ExtensionError('unknown encoding %r' % (encoding,))
raise ExtensionError(f'unknown encoding {encoding!r}')
data = data.decode('utf-8')
else:
with codecs.open(url, mode='r', encoding='utf-8') as fid:
Expand Down Expand Up @@ -123,7 +122,7 @@ def parse_sphinx_docopts(index):
return docopts


class SphinxDocLinkResolver(object):
class SphinxDocLinkResolver:
""" Resolve documentation links using searchindex.js generated by Sphinx

Parameters
Expand Down Expand Up @@ -299,10 +298,10 @@ def resolve(self, cobj, this_url, return_type=False):

def _handle_http_url_error(e, msg='fetching'):
if isinstance(e, HTTPError):
error_msg = '%s %s: %s (%s)' % (msg, e.url, e.code, e.msg)
error_msg = f'{msg} {e.url}: {e.code} ({e.msg})'
elif isinstance(e, URLError):
error_msg = '%s: %s' % (msg, e.reason)
logger.warning('The following %s has occurred %s' % (
error_msg = f'{msg}: {e.reason}'
logger.warning('The following {} has occurred {}'.format(
type(e).__name__, error_msg))


Expand Down Expand Up @@ -381,7 +380,7 @@ def _embed_code_links(app, gallery_conf, gallery_dir):
cobj, full_fname, return_type=True)
except (HTTPError, URLError) as e:
_handle_http_url_error(
e, msg='resolving %s.%s' % (modname, cname))
e, msg=f'resolving {modname}.{cname}')

# next try intersphinx
if this_module == modname == 'builtins':
Expand All @@ -393,7 +392,7 @@ def _embed_code_links(app, gallery_conf, gallery_dir):
if modname == 'builtins':
want = cname
else:
want = '%s.%s' % (modname, cname)
want = f'{modname}.{cname}'
for key, value in inv.items():
# only python domain
if key.startswith('py') and want in value:
Expand All @@ -410,7 +409,7 @@ def _embed_code_links(app, gallery_conf, gallery_dir):
# Add CSS classes
name_html = period.join(orig_pattern % part
for part in name.split('.'))
full_function_name = '%s.%s' % (modname, cname)
full_function_name = f'{modname}.{cname}'
css_class = ("sphx-glr-backref-module-" +
_sanitize_css_class(modname))
if type_ is not None:
Expand Down
2 changes: 0 additions & 2 deletions sphinx_gallery/downloads.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""
Utilities for downloadable items
================================
Expand All @@ -7,7 +6,6 @@
# Author: Óscar Nájera
# License: 3-clause BSD

from __future__ import absolute_import, division, print_function

import os
import zipfile
Expand Down
Loading