From bfaf390aa888c2c2e8bfbdd4e1ebb2af9376b55d Mon Sep 17 00:00:00 2001 From: Zac-HD Date: Fri, 11 May 2018 23:14:44 +1000 Subject: [PATCH 1/5] Remove no-op imports of `six` --- lib/matplotlib/__init__.py | 7 ------- lib/matplotlib/animation.py | 2 +- lib/matplotlib/backends/backend_agg.py | 2 -- lib/matplotlib/backends/backend_wxagg.py | 2 -- lib/matplotlib/tests/__init__.py | 2 -- lib/matplotlib/tests/test_backend_svg.py | 2 -- lib/matplotlib/tests/test_cbook.py | 2 -- lib/matplotlib/tests/test_constrainedlayout.py | 1 - lib/matplotlib/tests/test_container.py | 1 - lib/matplotlib/tests/test_mathtext.py | 2 -- lib/matplotlib/tests/test_pickle.py | 4 +--- lib/matplotlib/tests/test_png.py | 3 +-- lib/matplotlib/tests/test_table.py | 2 -- lib/matplotlib/tests/test_text.py | 2 -- lib/matplotlib/tests/test_tightlayout.py | 1 - lib/matplotlib/tests/test_transforms.py | 2 -- lib/matplotlib/tests/test_ttconv.py | 2 -- lib/matplotlib/tests/test_type1font.py | 2 -- lib/mpl_toolkits/axes_grid1/__init__.py | 2 -- lib/mpl_toolkits/axes_grid1/anchored_artists.py | 2 -- lib/mpl_toolkits/axes_grid1/axes_divider.py | 3 --- lib/mpl_toolkits/axes_grid1/axes_grid.py | 2 -- lib/mpl_toolkits/axes_grid1/inset_locator.py | 1 - lib/mpl_toolkits/axisartist/__init__.py | 2 -- lib/mpl_toolkits/axisartist/angle_helper.py | 2 -- lib/mpl_toolkits/axisartist/axis_artist.py | 2 -- lib/mpl_toolkits/axisartist/axisline_style.py | 2 -- lib/mpl_toolkits/axisartist/clip_path.py | 3 --- lib/mpl_toolkits/axisartist/grid_finder.py | 2 -- lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py | 3 --- lib/mpl_toolkits/mplot3d/__init__.py | 2 -- lib/mpl_toolkits/mplot3d/axis3d.py | 2 -- lib/mpl_toolkits/mplot3d/proj3d.py | 3 --- lib/mpl_toolkits/tests/test_axes_grid1.py | 2 -- 34 files changed, 3 insertions(+), 73 deletions(-) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 09856d9e1cfc..c2b25dbef222 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -102,8 +102,6 @@ # NOTE: This file must remain Python 2 compatible for the foreseeable future, # to ensure that we error out properly for existing editable installs. -import six - import sys if sys.version_info < (3, 5): # noqa: E402 raise ImportError(""" @@ -197,11 +195,6 @@ def compare_versions(a, b): raise ImportError("Matplotlib requires dateutil") -if not compare_versions(six.__version__, '1.10'): - raise ImportError( - "Matplotlib requires six>=1.10; you have %s" % six.__version__) - - try: import pyparsing except ImportError: diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index d5f022108833..32c9a8eca0a1 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -727,7 +727,7 @@ def output_args(self): def _init_from_registry(cls): if sys.platform != 'win32' or rcParams[cls.exec_key] != 'convert': return - from six.moves import winreg + import winreg for flag in (0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY): try: hkey = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, diff --git a/lib/matplotlib/backends/backend_agg.py b/lib/matplotlib/backends/backend_agg.py index c0b9512a1dbb..de865feefd82 100644 --- a/lib/matplotlib/backends/backend_agg.py +++ b/lib/matplotlib/backends/backend_agg.py @@ -19,8 +19,6 @@ * integrate screen dpi w/ ppi and text """ -import six - import threading import numpy as np from collections import OrderedDict diff --git a/lib/matplotlib/backends/backend_wxagg.py b/lib/matplotlib/backends/backend_wxagg.py index 927d68d7198a..054c87d72630 100644 --- a/lib/matplotlib/backends/backend_wxagg.py +++ b/lib/matplotlib/backends/backend_wxagg.py @@ -1,5 +1,3 @@ -import six - import wx import matplotlib diff --git a/lib/matplotlib/tests/__init__.py b/lib/matplotlib/tests/__init__.py index 9a4ca1e89fcf..855d68142300 100644 --- a/lib/matplotlib/tests/__init__.py +++ b/lib/matplotlib/tests/__init__.py @@ -1,5 +1,3 @@ -import six - import difflib import os diff --git a/lib/matplotlib/tests/test_backend_svg.py b/lib/matplotlib/tests/test_backend_svg.py index 8d98759b5915..2dc364404087 100644 --- a/lib/matplotlib/tests/test_backend_svg.py +++ b/lib/matplotlib/tests/test_backend_svg.py @@ -1,5 +1,3 @@ -import six - import numpy as np from io import BytesIO import os diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 8f414ea63998..745844fb6a1c 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -3,8 +3,6 @@ from weakref import ref import warnings -import six - from datetime import datetime import numpy as np diff --git a/lib/matplotlib/tests/test_constrainedlayout.py b/lib/matplotlib/tests/test_constrainedlayout.py index cb25d67756fa..7e922a7b9383 100644 --- a/lib/matplotlib/tests/test_constrainedlayout.py +++ b/lib/matplotlib/tests/test_constrainedlayout.py @@ -1,4 +1,3 @@ -import six import warnings import numpy as np diff --git a/lib/matplotlib/tests/test_container.py b/lib/matplotlib/tests/test_container.py index b035589f6ae0..8e894d9e9084 100644 --- a/lib/matplotlib/tests/test_container.py +++ b/lib/matplotlib/tests/test_container.py @@ -1,4 +1,3 @@ -import six import matplotlib.pyplot as plt diff --git a/lib/matplotlib/tests/test_mathtext.py b/lib/matplotlib/tests/test_mathtext.py index 5c1343b28718..e4feb8e17d3c 100644 --- a/lib/matplotlib/tests/test_mathtext.py +++ b/lib/matplotlib/tests/test_mathtext.py @@ -1,5 +1,3 @@ -import six - import io import re diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index e9240a118f9f..719dc7356fc8 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -1,6 +1,4 @@ -from six.moves import cPickle as pickle -from six.moves import range - +import pickle from io import BytesIO import numpy as np diff --git a/lib/matplotlib/tests/test_png.py b/lib/matplotlib/tests/test_png.py index 46bfae9891d5..508b46542885 100644 --- a/lib/matplotlib/tests/test_png.py +++ b/lib/matplotlib/tests/test_png.py @@ -1,5 +1,4 @@ -import six -from six import BytesIO +from io import BytesIO import glob import os import numpy as np diff --git a/lib/matplotlib/tests/test_table.py b/lib/matplotlib/tests/test_table.py index 3b452216eca2..83629eba0489 100644 --- a/lib/matplotlib/tests/test_table.py +++ b/lib/matplotlib/tests/test_table.py @@ -1,5 +1,3 @@ -import six - import matplotlib.pyplot as plt import numpy as np from matplotlib.testing.decorators import image_comparison diff --git a/lib/matplotlib/tests/test_text.py b/lib/matplotlib/tests/test_text.py index b756fb708041..4474099738c5 100644 --- a/lib/matplotlib/tests/test_text.py +++ b/lib/matplotlib/tests/test_text.py @@ -1,5 +1,3 @@ -import six - import io import warnings diff --git a/lib/matplotlib/tests/test_tightlayout.py b/lib/matplotlib/tests/test_tightlayout.py index 561635e8bf59..68139fc68c81 100644 --- a/lib/matplotlib/tests/test_tightlayout.py +++ b/lib/matplotlib/tests/test_tightlayout.py @@ -1,4 +1,3 @@ -import six import warnings import numpy as np diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 83fd0b51780e..52d2f2bfa749 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -1,5 +1,3 @@ -from six.moves import zip - import unittest import numpy as np diff --git a/lib/matplotlib/tests/test_ttconv.py b/lib/matplotlib/tests/test_ttconv.py index 083de831b430..6bb6feac74d5 100644 --- a/lib/matplotlib/tests/test_ttconv.py +++ b/lib/matplotlib/tests/test_ttconv.py @@ -1,5 +1,3 @@ -import six - import matplotlib from matplotlib.font_manager import FontProperties from matplotlib.testing.decorators import image_comparison diff --git a/lib/matplotlib/tests/test_type1font.py b/lib/matplotlib/tests/test_type1font.py index 2457c44b9e0f..3122fc5f8611 100644 --- a/lib/matplotlib/tests/test_type1font.py +++ b/lib/matplotlib/tests/test_type1font.py @@ -1,5 +1,3 @@ -import six - import matplotlib.type1font as t1f import os.path import difflib diff --git a/lib/mpl_toolkits/axes_grid1/__init__.py b/lib/mpl_toolkits/axes_grid1/__init__.py index 6750e13c174d..2109556cfe70 100644 --- a/lib/mpl_toolkits/axes_grid1/__init__.py +++ b/lib/mpl_toolkits/axes_grid1/__init__.py @@ -1,5 +1,3 @@ -import six - from . import axes_size as Size from .axes_divider import Divider, SubplotDivider, LocatableAxes, \ make_axes_locatable diff --git a/lib/mpl_toolkits/axes_grid1/anchored_artists.py b/lib/mpl_toolkits/axes_grid1/anchored_artists.py index 6aee423bcf1f..9355247ff157 100644 --- a/lib/mpl_toolkits/axes_grid1/anchored_artists.py +++ b/lib/mpl_toolkits/axes_grid1/anchored_artists.py @@ -1,5 +1,3 @@ -import six - from matplotlib import docstring, transforms from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox, DrawingArea, TextArea, VPacker) diff --git a/lib/mpl_toolkits/axes_grid1/axes_divider.py b/lib/mpl_toolkits/axes_grid1/axes_divider.py index fa96eebc9a18..ffda811efc40 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid1/axes_divider.py @@ -10,9 +10,6 @@ object that can be used to set the axes_locator of the axes. """ -import six -from six.moves import map - import matplotlib.transforms as mtransforms from matplotlib.axes import SubplotBase diff --git a/lib/mpl_toolkits/axes_grid1/axes_grid.py b/lib/mpl_toolkits/axes_grid1/axes_grid.py index 454fc9601068..7125704d3b4e 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_grid.py +++ b/lib/mpl_toolkits/axes_grid1/axes_grid.py @@ -1,5 +1,3 @@ -import six - from numbers import Number import matplotlib.axes as maxes diff --git a/lib/mpl_toolkits/axes_grid1/inset_locator.py b/lib/mpl_toolkits/axes_grid1/inset_locator.py index 75a6a90d7bb7..3737d44a0a21 100644 --- a/lib/mpl_toolkits/axes_grid1/inset_locator.py +++ b/lib/mpl_toolkits/axes_grid1/inset_locator.py @@ -2,7 +2,6 @@ A collection of functions and objects for creating or placing inset axes. """ from matplotlib import docstring -import six from matplotlib.offsetbox import AnchoredOffsetbox from matplotlib.patches import Patch, Rectangle from matplotlib.path import Path diff --git a/lib/mpl_toolkits/axisartist/__init__.py b/lib/mpl_toolkits/axisartist/__init__.py index 12c4ec6f95bd..9640fb916f1a 100644 --- a/lib/mpl_toolkits/axisartist/__init__.py +++ b/lib/mpl_toolkits/axisartist/__init__.py @@ -1,5 +1,3 @@ -import six - from .axislines import ( Axes, AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear, GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero) diff --git a/lib/mpl_toolkits/axisartist/angle_helper.py b/lib/mpl_toolkits/axisartist/angle_helper.py index 135785271b09..e222ce4e72b0 100644 --- a/lib/mpl_toolkits/axisartist/angle_helper.py +++ b/lib/mpl_toolkits/axisartist/angle_helper.py @@ -1,5 +1,3 @@ -import six - import numpy as np import math diff --git a/lib/mpl_toolkits/axisartist/axis_artist.py b/lib/mpl_toolkits/axisartist/axis_artist.py index 0cf14608d8ec..1eb91ff3af65 100644 --- a/lib/mpl_toolkits/axisartist/axis_artist.py +++ b/lib/mpl_toolkits/axisartist/axis_artist.py @@ -84,8 +84,6 @@ """ -import six - # FIXME : # angles are given in data coordinate - need to convert it to canvas coordinate diff --git a/lib/mpl_toolkits/axisartist/axisline_style.py b/lib/mpl_toolkits/axisartist/axisline_style.py index 38a00be95f7e..7c9c0a9711b6 100644 --- a/lib/mpl_toolkits/axisartist/axisline_style.py +++ b/lib/mpl_toolkits/axisartist/axisline_style.py @@ -1,5 +1,3 @@ -import six - from matplotlib.patches import _Style, FancyArrowPatch from matplotlib.transforms import IdentityTransform from matplotlib.path import Path diff --git a/lib/mpl_toolkits/axisartist/clip_path.py b/lib/mpl_toolkits/axisartist/clip_path.py index 57e961d7b2df..c51336e850ce 100644 --- a/lib/mpl_toolkits/axisartist/clip_path.py +++ b/lib/mpl_toolkits/axisartist/clip_path.py @@ -1,6 +1,3 @@ -import six -from six.moves import zip - import numpy as np from math import degrees import math diff --git a/lib/mpl_toolkits/axisartist/grid_finder.py b/lib/mpl_toolkits/axisartist/grid_finder.py index cd74a2e61004..97d2137a3769 100644 --- a/lib/mpl_toolkits/axisartist/grid_finder.py +++ b/lib/mpl_toolkits/axisartist/grid_finder.py @@ -1,5 +1,3 @@ -import six - import numpy as np from matplotlib.transforms import Bbox from . import clip_path diff --git a/lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py b/lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py index c0bd303e9a69..01dbd1eae1aa 100644 --- a/lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py +++ b/lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py @@ -1,9 +1,6 @@ """ An experimental support for curvilinear grid. """ -import six -from six.moves import zip - from itertools import chain from .grid_finder import GridFinder diff --git a/lib/mpl_toolkits/mplot3d/__init__.py b/lib/mpl_toolkits/mplot3d/__init__.py index 86ea3faffb3e..30e682aea018 100644 --- a/lib/mpl_toolkits/mplot3d/__init__.py +++ b/lib/mpl_toolkits/mplot3d/__init__.py @@ -1,3 +1 @@ -import six - from .axes3d import Axes3D diff --git a/lib/mpl_toolkits/mplot3d/axis3d.py b/lib/mpl_toolkits/mplot3d/axis3d.py index 8a431c1a0854..57545fd1a125 100644 --- a/lib/mpl_toolkits/mplot3d/axis3d.py +++ b/lib/mpl_toolkits/mplot3d/axis3d.py @@ -2,8 +2,6 @@ # Created: 23 Sep 2005 # Parts rewritten by Reinier Heeres -import six - import copy from matplotlib import ( diff --git a/lib/mpl_toolkits/mplot3d/proj3d.py b/lib/mpl_toolkits/mplot3d/proj3d.py index 404b52095cea..4a26d13b953b 100644 --- a/lib/mpl_toolkits/mplot3d/proj3d.py +++ b/lib/mpl_toolkits/mplot3d/proj3d.py @@ -3,9 +3,6 @@ """ Various transforms used for by the 3D code """ -import six -from six.moves import zip - import numpy as np import numpy.linalg as linalg diff --git a/lib/mpl_toolkits/tests/test_axes_grid1.py b/lib/mpl_toolkits/tests/test_axes_grid1.py index 685f103930b9..14648956a566 100644 --- a/lib/mpl_toolkits/tests/test_axes_grid1.py +++ b/lib/mpl_toolkits/tests/test_axes_grid1.py @@ -1,5 +1,3 @@ -import six - import matplotlib import matplotlib.pyplot as plt from matplotlib.testing.decorators import image_comparison From bd508b998a34f9af8bc7482b0ef2508db7961882 Mon Sep 17 00:00:00 2001 From: Zac-HD Date: Fri, 11 May 2018 23:20:24 +1000 Subject: [PATCH 2/5] Strip out obsolete compatibility layer from `six` --- lib/matplotlib/artist.py | 13 ++-- lib/matplotlib/backend_bases.py | 10 ++- lib/matplotlib/backends/_backend_tk.py | 29 ++++---- lib/matplotlib/backends/backend_cairo.py | 13 +--- lib/matplotlib/backends/backend_ps.py | 26 +++---- lib/matplotlib/backends/backend_svg.py | 68 +++++++------------ lib/matplotlib/backends/backend_wx.py | 6 +- lib/matplotlib/dviread.py | 2 +- lib/matplotlib/lines.py | 8 +-- lib/matplotlib/mlab.py | 33 +++------ lib/matplotlib/patches.py | 24 ++----- lib/matplotlib/rcsetup.py | 46 ++++++------- lib/matplotlib/sphinxext/plot_directive.py | 39 ++++------- lib/matplotlib/tests/test_axes.py | 6 +- lib/matplotlib/tests/test_basic.py | 10 +-- lib/matplotlib/tests/test_colors.py | 7 +- lib/matplotlib/tests/test_mlab.py | 8 +-- lib/matplotlib/tests/test_patches.py | 6 +- lib/matplotlib/tests/test_rcparams.py | 7 +- lib/matplotlib/tests/test_style.py | 4 +- lib/matplotlib/ticker.py | 23 +++---- lib/matplotlib/type1font.py | 10 +-- lib/mpl_toolkits/axes_grid1/axes_rgb.py | 14 ++-- lib/mpl_toolkits/axes_grid1/axes_size.py | 4 +- lib/mpl_toolkits/axes_grid1/colorbar.py | 9 +-- lib/mpl_toolkits/axes_grid1/mpl_axes.py | 5 +- lib/mpl_toolkits/axisartist/axislines.py | 4 +- lib/mpl_toolkits/mplot3d/axes3d.py | 6 +- .../tests/test_axisartist_clip_path.py | 4 +- tools/gh_api.py | 4 +- tools/make_icons.py | 4 +- 31 files changed, 153 insertions(+), 299 deletions(-) diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index f26b8dcbb901..6975af34f055 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -1,5 +1,3 @@ -import six - from collections import OrderedDict, namedtuple from functools import wraps import inspect @@ -286,7 +284,7 @@ def pchanged(self): Fire an event when property changed, calling all of the registered callbacks. """ - for oid, func in six.iteritems(self._propobservers): + for oid, func in self._propobservers.items(): func(self) def is_transform_set(self): @@ -902,7 +900,7 @@ def set_label(self, s): .. ACCEPTS: object """ if s is not None: - self._label = six.text_type(s) + self._label = str(s) else: self._label = None self.pchanged() @@ -1152,10 +1150,7 @@ def _get_setters_and_targets(self): func = getattr(self.o, name) if not callable(func): continue - if six.PY2: - nargs = len(inspect.getargspec(func)[0]) - else: - nargs = len(inspect.getfullargspec(func)[0]) + nargs = len(inspect.getfullargspec(func).args) if nargs < 2 or self.is_alias(func): continue source_class = self.o.__module__ + "." + self.o.__name__ @@ -1325,7 +1320,7 @@ def pprint_getters(self): """ lines = [] - for name, val in sorted(six.iteritems(self.properties())): + for name, val in sorted(self.properties().items()): if getattr(val, 'shape', ()) != () and len(val) > 6: s = str(val[:6]) + '...' else: diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index f79cdbfe44f3..caf773a1e518 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -32,8 +32,6 @@ The base class for the messaging area. """ -import six - from contextlib import contextmanager from functools import partial import importlib @@ -121,7 +119,7 @@ def get_registered_canvas_class(format): if format not in _default_backends: return None backend_class = _default_backends[format] - if isinstance(backend_class, six.string_types): + if isinstance(backend_class, str): backend_class = importlib.import_module(backend_class).FigureCanvas _default_backends[format] = backend_class return backend_class @@ -2059,7 +2057,7 @@ def get_supported_filetypes_grouped(cls): Experts Group', and the values are a list of filename extensions used for that filetype, such as ['jpg', 'jpeg'].""" groupings = {} - for ext, name in six.iteritems(cls.filetypes): + for ext, name in cls.filetypes.items(): groupings.setdefault(name, []).append(ext) groupings[name].sort() return groupings @@ -2130,11 +2128,11 @@ def print_figure(self, filename, dpi=None, facecolor=None, edgecolor=None, # get format from filename, or from backend's default filetype if isinstance(filename, getattr(os, "PathLike", ())): filename = os.fspath(filename) - if isinstance(filename, six.string_types): + if isinstance(filename, str): format = os.path.splitext(filename)[1][1:] if format is None or format == '': format = self.get_default_filetype() - if isinstance(filename, six.string_types): + if isinstance(filename, str): filename = filename.rstrip('.') + '.' + format format = format.lower() diff --git a/lib/matplotlib/backends/_backend_tk.py b/lib/matplotlib/backends/_backend_tk.py index 601e5fb6e2cf..4fb68a835fb7 100644 --- a/lib/matplotlib/backends/_backend_tk.py +++ b/lib/matplotlib/backends/_backend_tk.py @@ -1,5 +1,3 @@ -import six - import math import logging import os.path @@ -58,14 +56,14 @@ def _restore_foreground_window_at_end(): def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines""" - if not isinstance(msg, six.string_types): + if not isinstance(msg, str): msg = '\n'.join(map(str, msg)) return msg def error_msg_tkpaint(msg, parent=None): - from six.moves import tkinter_messagebox as tkMessageBox - tkMessageBox.showerror("matplotlib", msg) + import tkinter.messagebox + tkinter.messagebox.showerror("matplotlib", msg) def blit(photoimage, aggimage, offsets, bbox=None): @@ -686,7 +684,7 @@ def configure_subplots(self): window.grab_set() def save_figure(self, *args): - from six.moves import tkinter_tkfiledialog, tkinter_messagebox + import tkinter.filedialog, tkinter.messagebox filetypes = self.canvas.get_supported_filetypes().copy() default_filetype = self.canvas.get_default_filetype() @@ -694,7 +692,7 @@ def save_figure(self, *args): # so we just have to put it first default_filetype_name = filetypes.pop(default_filetype) sorted_filetypes = ([(default_filetype, default_filetype_name)] - + sorted(six.iteritems(filetypes))) + + sorted(filetypes.items())) tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes] # adding a default extension seems to break the @@ -705,7 +703,7 @@ def save_figure(self, *args): defaultextension = '' initialdir = os.path.expanduser(rcParams['savefig.directory']) initialfile = self.canvas.get_default_filename() - fname = tkinter_tkfiledialog.asksaveasfilename( + fname = tkinter.filedialog.asksaveasfilename( master=self.window, title='Save the figure', filetypes=tk_filetypes, @@ -719,12 +717,12 @@ def save_figure(self, *args): # Save dir for next time, unless empty str (i.e., use cwd). if initialdir != "": rcParams['savefig.directory'] = ( - os.path.dirname(six.text_type(fname))) + os.path.dirname(str(fname))) try: # This method will handle the delegation to the correct type self.canvas.figure.savefig(fname) except Exception as e: - tkinter_messagebox.showerror("Error saving file", str(e)) + tkinter.messagebox.showerror("Error saving file", str(e)) def set_active(self, ind): self._ind = ind @@ -906,7 +904,7 @@ def set_message(self, s): class SaveFigureTk(backend_tools.SaveFigureBase): def trigger(self, *args): - from six.moves import tkinter_tkfiledialog, tkinter_messagebox + import tkinter.filedialog, tkinter.messagebox filetypes = self.figure.canvas.get_supported_filetypes().copy() default_filetype = self.figure.canvas.get_default_filetype() @@ -914,7 +912,7 @@ def trigger(self, *args): # so we just have to put it first default_filetype_name = filetypes.pop(default_filetype) sorted_filetypes = ([(default_filetype, default_filetype_name)] - + sorted(six.iteritems(filetypes))) + + sorted(filetypes.items())) tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes] # adding a default extension seems to break the @@ -925,7 +923,7 @@ def trigger(self, *args): defaultextension = '' initialdir = os.path.expanduser(rcParams['savefig.directory']) initialfile = self.figure.canvas.get_default_filename() - fname = tkinter_tkfiledialog.asksaveasfilename( + fname = tkinter.filedialog.asksaveasfilename( master=self.figure.canvas.manager.window, title='Save the figure', filetypes=tk_filetypes, @@ -942,13 +940,12 @@ def trigger(self, *args): rcParams['savefig.directory'] = initialdir else: # save dir for next time - rcParams['savefig.directory'] = os.path.dirname( - six.text_type(fname)) + rcParams['savefig.directory'] = os.path.dirname(str(fname)) try: # This method will handle the delegation to the correct type self.figure.savefig(fname) except Exception as e: - tkinter_messagebox.showerror("Error saving file", str(e)) + tkinter.messagebox.showerror("Error saving file", str(e)) class ConfigureSubplotsTk(backend_tools.ConfigureSubplotsBase): diff --git a/lib/matplotlib/backends/backend_cairo.py b/lib/matplotlib/backends/backend_cairo.py index 189f29671aee..4ac358d35503 100644 --- a/lib/matplotlib/backends/backend_cairo.py +++ b/lib/matplotlib/backends/backend_cairo.py @@ -6,8 +6,6 @@ This backend depends on cairocffi or pycairo. """ -import six - import copy import gzip import sys @@ -395,13 +393,6 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): ctx.rotate(np.deg2rad(-angle)) ctx.set_font_size(size) - if HAS_CAIRO_CFFI: - if not isinstance(s, six.text_type): - s = six.text_type(s) - else: - if six.PY2 and isinstance(s, six.text_type): - s = s.encode("utf-8") - ctx.show_text(s) ctx.restore() @@ -426,8 +417,6 @@ def _draw_mathtext(self, gc, x, y, s, prop, angle): size = fontsize * self.dpi / 72.0 ctx.set_font_size(size) - if not six.PY3 and isinstance(s, six.text_type): - s = s.encode("utf-8") ctx.show_text(s) for ox, oy, w, h in rects: @@ -631,7 +620,7 @@ def _save(self, fo, fmt, **kwargs): raise RuntimeError('cairo has not been compiled with SVG ' 'support enabled') if fmt == 'svgz': - if isinstance(fo, six.string_types): + if isinstance(fo, str): fo = gzip.GzipFile(fo, 'wb') else: fo = gzip.GzipFile(None, 'wb', fileobj=fo) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index e02b37df7c5c..7109781a5330 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1,9 +1,6 @@ """ A PostScript backend, which can produce both PostScript .ps and .eps """ -import six -from six.moves import StringIO - import glob, os, shutil, sys, time, datetime import io import logging @@ -77,10 +74,7 @@ def gs_version(self): s = subprocess.Popen( [self.gs_exe, "--version"], stdout=subprocess.PIPE) pipe, stderr = s.communicate() - if six.PY3: - ver = pipe.decode('ascii') - else: - ver = pipe + ver = pipe.decode('ascii') try: gs_version = tuple(map(int, ver.strip().split("."))) except ValueError: @@ -133,7 +127,7 @@ def _get_papertype(w, h): return 'a0' def _num_to_str(val): - if isinstance(val, six.string_types): + if isinstance(val, str): return val ival = int(val) @@ -229,7 +223,7 @@ def track_characters(self, font, s): used_characters[1].update(map(ord, s)) def merge_used_characters(self, other): - for stat_key, (realpath, charset) in six.iteritems(other): + for stat_key, (realpath, charset) in other.items(): used_characters = self.used_characters.setdefault( stat_key, (realpath, set())) used_characters[1].update(charset) @@ -981,8 +975,7 @@ def _print_figure( the key 'Creator' is used. """ isEPSF = format == 'eps' - if isinstance(outfile, - (six.string_types, getattr(os, "PathLike", ()),)): + if isinstance(outfile, (str, getattr(os, "PathLike", ()),)): outfile = title = getattr(os, "fspath", lambda obj: obj)(outfile) title = title.encode("latin-1", "replace").decode() passed_in_file_object = False @@ -1102,8 +1095,8 @@ def print_figure_impl(fh): for l in d.split('\n'): print(l.strip(), file=fh) if not rcParams['ps.useafm']: - for font_filename, chars in six.itervalues( - ps_renderer.used_characters): + for font_filename, chars in \ + ps_renderer.used_characters.values(): if len(chars): font = get_font(font_filename) glyph_ids = [] @@ -1148,7 +1141,7 @@ def print_figure_impl(fh): # write the figure content = self._pswriter.getvalue() - if not isinstance(content, six.text_type): + if not isinstance(content, str): content = content.decode('ascii') print(content, file=fh) @@ -1181,8 +1174,7 @@ def print_figure_impl(fh): if passed_in_file_object: requires_unicode = file_requires_unicode(outfile) - if (not requires_unicode and - (six.PY3 or not isinstance(outfile, StringIO))): + if not requires_unicode: fh = io.TextIOWrapper(outfile, encoding="latin-1") # Prevent the io.TextIOWrapper from closing the @@ -1211,7 +1203,7 @@ def _print_figure_tex( the key 'Creator' is used. """ isEPSF = format == 'eps' - if isinstance(outfile, six.string_types): + if isinstance(outfile, str): title = outfile elif is_writable_file_like(outfile): title = None diff --git a/lib/matplotlib/backends/backend_svg.py b/lib/matplotlib/backends/backend_svg.py index 12a6c0733e73..06ea019b5fce 100644 --- a/lib/matplotlib/backends/backend_svg.py +++ b/lib/matplotlib/backends/backend_svg.py @@ -1,10 +1,6 @@ from collections import OrderedDict -import six -from six import unichr - import base64 -import codecs import gzip import hashlib import io @@ -238,7 +234,7 @@ def generate_transform(transform_list=[]): def generate_css(attrib={}): if attrib: output = io.StringIO() - attrib = sorted(six.iteritems(attrib)) + attrib = sorted(attrib.items()) for k, v in attrib: k = escape_attrib(k) v = escape_attrib(v) @@ -304,17 +300,12 @@ def _write_default_style(self): writer.end('defs') def _make_id(self, type, content): - content = str(content) - if rcParams['svg.hashsalt'] is None: + salt = rcParams['svg.hashsalt'] + if salt is None: salt = str(uuid.uuid4()) - else: - salt = rcParams['svg.hashsalt'] - if six.PY3: - content = content.encode('utf8') - salt = salt.encode('utf8') m = hashlib.md5() - m.update(salt) - m.update(content) + m.update(salt.encode('utf8')) + m.update(str(content).encode('utf8')) return '%s%s' % (type, m.hexdigest()[:10]) def _make_flip_transform(self, transform): @@ -355,13 +346,13 @@ def _write_hatches(self): HATCH_SIZE = 72 writer = self.writer writer.start('defs') - for ((path, face, stroke), oid) in six.itervalues(self._hatchd): + for (path, face, stroke), oid in self._hatchd.values(): writer.start( 'pattern', id=oid, patternUnits="userSpaceOnUse", - x="0", y="0", width=six.text_type(HATCH_SIZE), - height=six.text_type(HATCH_SIZE)) + x="0", y="0", width=str(HATCH_SIZE), + height=str(HATCH_SIZE)) path_data = self._convert_path( path, Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE), @@ -372,8 +363,8 @@ def _write_hatches(self): fill = rgb2hex(face) writer.element( 'rect', - x="0", y="0", width=six.text_type(HATCH_SIZE+1), - height=six.text_type(HATCH_SIZE+1), + x="0", y="0", width=str(HATCH_SIZE+1), + height=str(HATCH_SIZE+1), fill=fill) writer.element( 'path', @@ -381,7 +372,7 @@ def _write_hatches(self): style=generate_css({ 'fill': rgb2hex(stroke), 'stroke': rgb2hex(stroke), - 'stroke-width': six.text_type(rcParams['hatch.linewidth']), + 'stroke-width': str(rcParams['hatch.linewidth']), 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' }) @@ -466,7 +457,7 @@ def _write_clips(self): return writer = self.writer writer.start('defs') - for clip, oid in six.itervalues(self._clipd): + for clip, oid in self._clipd.values(): writer.start('clipPath', id=oid) if len(clip) == 2: clippath, clippath_trans = clip @@ -489,7 +480,7 @@ def _write_svgfonts(self): writer = self.writer writer.start('defs') - for font_fname, chars in six.iteritems(self._fonts): + for font_fname, chars in self._fonts.items(): font = get_font(font_fname) font.set_size(72, 72) sfnt = font.get_sfnt() @@ -513,7 +504,7 @@ def _write_svgfonts(self): d=path_data, attrib={ # 'glyph-name': name, - 'unicode': unichr(char), + 'unicode': chr(char), 'horiz-adv-x': short_float_fmt(glyph.linearHoriAdvance / 65536.0)}) writer.end('font') @@ -583,7 +574,7 @@ def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None) style = self._get_style_dict(gc, rgbFace) dictkey = (path_data, generate_css(style)) oid = self._markers.get(dictkey) - style = generate_css({k: v for k, v in six.iteritems(style) + style = generate_css({k: v for k, v in style.items() if k.startswith('stroke')}) if oid is None: @@ -907,7 +898,7 @@ def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None): if glyph_map_new: writer.start('defs') - for char_id, glyph_path in six.iteritems(glyph_map_new): + for char_id, glyph_path in glyph_map_new.items(): path = Path(*glyph_path) path_data = self._convert_path(path, simplify=False) writer.element('path', id=char_id, d=path_data) @@ -950,7 +941,7 @@ def _draw_text_as_path(self, gc, x, y, s, prop, angle, ismath, mtext=None): # used. if glyph_map_new: writer.start('defs') - for char_id, glyph_path in six.iteritems(glyph_map_new): + for char_id, glyph_path in glyph_map_new.items(): char_id = self._adjust_char_id(char_id) # Some characters are blank if not len(glyph_path[0]): @@ -1014,9 +1005,9 @@ def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): attrib = {} # Must add "px" to workaround a Firefox bug style['font-size'] = short_float_fmt(fontsize) + 'px' - style['font-family'] = six.text_type(fontfamily) + style['font-family'] = str(fontfamily) style['font-style'] = prop.get_style().lower() - style['font-weight'] = six.text_type(prop.get_weight()).lower() + style['font-weight'] = str(prop.get_weight()).lower() attrib['style'] = generate_css(style) if mtext and (angle == 0 or mtext.get_rotation_mode() == "anchor"): @@ -1097,7 +1088,7 @@ def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): fontset = self._fonts.setdefault(font.fname, set()) fontset.add(thetext) - for style, chars in six.iteritems(spans): + for style, chars in spans.items(): chars.sort() same_y = True @@ -1108,9 +1099,9 @@ def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): same_y = False break if same_y: - ys = six.text_type(chars[0][1]) + ys = str(chars[0][1]) else: - ys = ' '.join(six.text_type(c[1]) for c in chars) + ys = ' '.join(str(c[1]) for c in chars) attrib = { 'style': style, @@ -1120,7 +1111,7 @@ def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None): writer.element( 'tspan', - ''.join(unichr(c[2]) for c in chars), + ''.join(chr(c[2]) for c in chars), attrib=attrib) writer.end('text') @@ -1182,16 +1173,13 @@ def print_svg(self, filename, *args, **kwargs): with cbook.open_file_cm(filename, "w", encoding="utf-8") as fh: filename = getattr(fh, 'name', '') - if not isinstance(filename, six.string_types): + if not isinstance(filename, str): filename = '' if cbook.file_requires_unicode(fh): detach = False else: - if six.PY3: - fh = io.TextIOWrapper(fh, 'utf-8') - else: - fh = codecs.getwriter('utf-8')(fh) + fh = io.TextIOWrapper(fh, 'utf-8') detach = True result = self._print_svg(filename, fh, **kwargs) @@ -1199,11 +1187,7 @@ def print_svg(self, filename, *args, **kwargs): # Detach underlying stream from wrapper so that it remains open in # the caller. if detach: - if six.PY3: - fh.detach() - else: - fh.reset() - fh.stream = io.BytesIO() + fh.detach() return result diff --git a/lib/matplotlib/backends/backend_wx.py b/lib/matplotlib/backends/backend_wx.py index 8842f0f8a75c..7c684e76cdd9 100644 --- a/lib/matplotlib/backends/backend_wx.py +++ b/lib/matplotlib/backends/backend_wx.py @@ -7,8 +7,6 @@ Copyright (C) Jeremy O'Donoghue & John Hunter, 2003-4. """ -import six - import os.path import math import sys @@ -97,7 +95,7 @@ def error_msg_wx(msg, parent=None): def raise_msg_to_str(msg): """msg is a return arg from a raise. Join with new lines.""" - if not isinstance(msg, six.string_types): + if not isinstance(msg, str): msg = '\n'.join(map(str, msg)) return msg @@ -1108,7 +1106,7 @@ def _print_image(self, filename, filetype, *args, **kwargs): # Now that we have rendered into the bitmap, save it # to the appropriate file type and clean up - if isinstance(filename, six.string_types): + if isinstance(filename, str): if not image.SaveFile(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError( diff --git a/lib/matplotlib/dviread.py b/lib/matplotlib/dviread.py index a45f17a2bc8c..a702f5585bc7 100644 --- a/lib/matplotlib/dviread.py +++ b/lib/matplotlib/dviread.py @@ -179,7 +179,7 @@ class Dvi(object): >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi: >>> for page in dvi: - >>> print(''.join(unichr(t.glyph) for t in page.text)) + >>> print(''.join(chr(t.glyph) for t in page.text)) """ # dispatch table _dtable = [None] * 256 diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index f90ce0159323..b9769574dc90 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -4,8 +4,6 @@ """ # TODO: expose cap and join style attrs -import six - from numbers import Number import warnings @@ -33,7 +31,7 @@ def _get_dash_pattern(style): """Convert linestyle -> dash pattern """ # go from short hand -> full strings - if isinstance(style, six.string_types): + if isinstance(style, str): style = ls_mapper.get(style, style) # un-dashed styles if style in ['solid', 'None']: @@ -351,7 +349,7 @@ def __init__(self, xdata, ydata, if solid_joinstyle is None: solid_joinstyle = rcParams['lines.solid_joinstyle'] - if isinstance(linestyle, six.string_types): + if isinstance(linestyle, str): ds, ls = self._split_drawstyle_linestyle(linestyle) if ds is not None and drawstyle is not None and ds != drawstyle: raise ValueError("Inconsistent drawstyle ({!r}) and linestyle " @@ -1074,7 +1072,7 @@ def set_linestyle(self, ls): ls : { ``'-'``, ``'--'``, ``'-.'``, ``':'``} and more see description The line style. """ - if isinstance(ls, six.string_types): + if isinstance(ls, str): ds, ls = self._split_drawstyle_linestyle(ls) if ds is not None: self.set_drawstyle(ds) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index ba01b28eb827..cbb479ab359a 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -154,9 +154,6 @@ """ -import six -from six.moves import map, zip - import copy import csv import operator @@ -171,10 +168,6 @@ import math -if six.PY3: - long = int - - @cbook.deprecated("2.2", alternative='numpy.logspace or numpy.geomspace') def logspace(xmin, xmax, N): ''' @@ -301,7 +294,7 @@ def detrend(x, key=None, axis=None): return detrend(x, key=detrend_linear, axis=axis) elif key == 'none': return detrend(x, key=detrend_none, axis=axis) - elif isinstance(key, six.string_types): + elif isinstance(key, str): raise ValueError("Unknown value for key %s, must be one of: " "'default', 'constant', 'mean', " "'linear', or a function" % key) @@ -2227,7 +2220,7 @@ def base_repr(number, base=2, padding=0): if number < base: return (padding - 1) * chars[0] + chars[int(number)] max_exponent = int(math.log(number)/math.log(base)) - max_power = long(base) ** max_exponent + max_power = int(base) ** max_exponent lead_digit = int(number/max_power) return (chars[lead_digit] + base_repr(number - max_power * lead_digit, base, @@ -2311,7 +2304,7 @@ def isvector(X): @cbook.deprecated("2.2", 'numpy.isnan') def safe_isnan(x): ':func:`numpy.isnan` for arbitrary types' - if isinstance(x, six.string_types): + if isinstance(x, str): return False try: b = np.isnan(x) @@ -2326,7 +2319,7 @@ def safe_isnan(x): @cbook.deprecated("2.2", 'numpy.isinf') def safe_isinf(x): ':func:`numpy.isinf` for arbitrary types' - if isinstance(x, six.string_types): + if isinstance(x, str): return False try: b = np.isinf(x) @@ -2346,8 +2339,8 @@ def rec_append_fields(rec, names, arrs, dtypes=None): *arrs* and *dtypes* do not have to be lists. They can just be the values themselves. """ - if (not isinstance(names, six.string_types) and cbook.iterable(names) - and len(names) and isinstance(names[0], six.string_types)): + if (not isinstance(names, str) and cbook.iterable(names) + and len(names) and isinstance(names[0], str)): if len(names) != len(arrs): raise ValueError("number of arrays do not match number of names") else: # we have only 1 name and 1 array @@ -2364,8 +2357,6 @@ def rec_append_fields(rec, names, arrs, dtypes=None): else: raise ValueError("dtypes must be None, a single dtype or a list") old_dtypes = rec.dtype.descr - if six.PY2: - old_dtypes = [(name.encode('utf-8'), dt) for name, dt in old_dtypes] newdtype = np.dtype(old_dtypes + list(zip(names, dtypes))) newrec = np.recarray(rec.shape, dtype=newdtype) for field in rec.dtype.fields: @@ -2399,7 +2390,7 @@ def rec_keep_fields(rec, names): Return a new numpy record array with only fields listed in names """ - if isinstance(names, six.string_types): + if isinstance(names, str): names = names.split(',') arrays = [] @@ -2499,7 +2490,7 @@ def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', (other than keys) that are both in *r1* and *r2*. """ - if isinstance(key, six.string_types): + if isinstance(key, str): key = (key, ) for name in key: @@ -2576,8 +2567,6 @@ def mapped_r2field(name): r2desc = [(mapped_r2field(desc[0]), desc[1]) for desc in r2.dtype.descr if desc[0] not in key] all_dtypes = keydesc + r1desc + r2desc - if six.PY2: - all_dtypes = [(name.encode('utf-8'), dt) for name, dt in all_dtypes] newdtype = np.dtype(all_dtypes) newrec = np.recarray((common_len + left_len + right_len,), dtype=newdtype) @@ -2595,7 +2584,7 @@ def mapped_r2field(name): if jointype != 'inner' and defaults is not None: # fill in the defaults enmasse newrec_fields = list(newrec.dtype.fields) - for k, v in six.iteritems(defaults): + for k, v in defaults.items(): if k in newrec_fields: newrec[k] = v @@ -2911,7 +2900,7 @@ def get_converters(reader, comments): seen[item] = cnt+1 else: - if isinstance(names, six.string_types): + if isinstance(names, str): names = [n.strip() for n in names.split(',')] # get the converter functions by inspecting checkrows @@ -3677,7 +3666,7 @@ def __init__(self, dataset, bw_method=None): raise ValueError("`dataset` input should have multiple elements.") self.dim, self.num_dp = np.array(self.dataset).shape - isString = isinstance(bw_method, six.string_types) + isString = isinstance(bw_method, str) if bw_method is None: pass diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 1078eb9953d0..6361451d6d83 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1,6 +1,3 @@ -import six -from six.moves import map, zip - import math from numbers import Number import warnings @@ -1848,24 +1845,13 @@ def _pprint_styles(_styles): _table = [["Class", "Name", "Attrs"]] for name, cls in sorted(_styles.items()): - if six.PY2: - args, varargs, varkw, defaults = inspect.getargspec(cls.__init__) - else: - (args, varargs, varkw, defaults, kwonlyargs, kwonlydefs, - annotations) = inspect.getfullargspec(cls.__init__) - if defaults: - args = [(argname, argdefault) - for argname, argdefault in zip(args[1:], defaults)] + spec = inspect.getfullargspec(cls.__init__) + if spec.defaults: + argstr = ",".join("%s=%s" % pair + for pair in zip(spec.args[-len(spec.defaults):], + spec.defaults)) else: - args = None - - if args is None: argstr = 'None' - else: - argstr = ",".join([("%s=%s" % (an, av)) - for an, av - in args]) - # adding ``quotes`` since - and | have special meaning in reST _table.append([cls.__name__, "``%s``" % name, argstr]) diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index d3ea5a7120cd..1b92692e2f94 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -13,8 +13,6 @@ parameter set listed here should also be visited to the :file:`matplotlibrc.template` in matplotlib's root source directory. """ -import six - from collections import Iterable, Mapping from functools import reduce import operator @@ -64,12 +62,12 @@ def __call__(self, s): if s in self.valid: return self.valid[s] raise ValueError('Unrecognized %s string %r: valid strings are %s' - % (self.key, s, list(six.itervalues(self.valid)))) + % (self.key, s, list(self.valid.values()))) def _listify_validator(scalar_validator, allow_stringlist=False): def f(s): - if isinstance(s, six.string_types): + if isinstance(s, str): try: return [scalar_validator(v.strip()) for v in s.split(',') if v.strip()] @@ -90,7 +88,7 @@ def f(s): # from the original validate_stringlist()), while allowing # any non-string/text scalar values such as numbers and arrays. return [scalar_validator(v) for v in s - if not isinstance(v, six.string_types) or v] + if not isinstance(v, str) or v] else: raise ValueError("{!r} must be of type: string or non-dictionary " "iterable".format(s)) @@ -119,7 +117,7 @@ def validate_path_exists(s): def validate_bool(b): """Convert b to a boolean or raise""" - if isinstance(b, six.string_types): + if isinstance(b, str): b = b.lower() if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True): return True @@ -131,7 +129,7 @@ def validate_bool(b): def validate_bool_maybe_none(b): 'Convert b to a boolean or raise' - if isinstance(b, six.string_types): + if isinstance(b, str): b = b.lower() if b is None or b == 'none': return None @@ -181,7 +179,7 @@ def validate_axisbelow(s): try: return validate_bool(s) except ValueError: - if isinstance(s, six.string_types): + if isinstance(s, str): s = s.lower() if s.startswith('line'): return 'line' @@ -236,10 +234,10 @@ def validate_fonttype(s): raise ValueError( 'Supported Postscript/PDF font types are %s' % list(fonttypes)) else: - if fonttype not in six.itervalues(fonttypes): + if fonttype not in fonttypes.values(): raise ValueError( 'Supported Postscript/PDF font types are %s' % - list(six.itervalues(fonttypes))) + list(fonttypes.values())) return fonttype @@ -288,7 +286,7 @@ def __init__(self, n=None, allow_none=False): def __call__(self, s): """return a seq of n floats or raise""" - if isinstance(s, six.string_types): + if isinstance(s, str): s = [x.strip() for x in s.split(',')] err_msg = _str_err_msg else: @@ -312,7 +310,7 @@ def __init__(self, n=None): def __call__(self, s): """return a seq of n ints or raise""" - if isinstance(s, six.string_types): + if isinstance(s, str): s = [x.strip() for x in s.split(',')] err_msg = _str_err_msg else: @@ -348,7 +346,7 @@ def validate_color_for_prop_cycle(s): if match is not None: raise ValueError('Can not put cycle reference ({cn!r}) in ' 'prop_cycler'.format(cn=s)) - elif isinstance(s, six.string_types): + elif isinstance(s, str): match = re.match('^C[0-9]$', s) if match is not None: raise ValueError('Can not put cycle reference ({cn!r}) in ' @@ -364,7 +362,7 @@ def validate_color(s): except AttributeError: pass - if isinstance(s, six.string_types): + if isinstance(s, str): if len(s) == 6 or len(s) == 8: stmp = '#' + s if is_color_like(stmp): @@ -398,7 +396,7 @@ def validate_color(s): validate_colorlist.__doc__ = 'return a list of colorspecs' def validate_string(s): - if isinstance(s, (str, six.text_type)): + if isinstance(s, (str, str)): # Always leave str as str and unicode as unicode return s else: @@ -430,7 +428,7 @@ def validate_fontsize_None(s): def validate_fontsize(s): fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'smaller', 'larger'] - if isinstance(s, six.string_types): + if isinstance(s, str): s = s.lower() if s in fontsizes: return s @@ -500,7 +498,7 @@ def update_savefig_format(value): def validate_ps_distiller(s): - if isinstance(s, six.string_types): + if isinstance(s, str): s = s.lower() if s in ('none', None): return None @@ -630,7 +628,7 @@ def validate_hinting(s): ['html5', 'jshtml', 'none']) def validate_bbox(s): - if isinstance(s, six.string_types): + if isinstance(s, str): s = s.lower() if s == 'tight': return s @@ -643,11 +641,11 @@ def validate_bbox(s): return s def validate_sketch(s): - if isinstance(s, six.string_types): + if isinstance(s, str): s = s.lower() if s == 'none' or s is None: return None - if isinstance(s, six.string_types): + if isinstance(s, str): result = tuple([float(v.strip()) for v in s.split(',')]) elif isinstance(s, (list, tuple)): result = tuple([float(v) for v in s]) @@ -696,7 +694,7 @@ def validate_hatch(s): characters: ``\\ / | - + * . x o O``. """ - if not isinstance(s, six.string_types): + if not isinstance(s, str): raise ValueError("Hatch pattern must be a string") unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'} if unknown: @@ -807,7 +805,7 @@ def cycler(*args, **kwargs): elif len(args) > 2: raise TypeError("No more than 2 positional arguments allowed") else: - pairs = six.iteritems(kwargs) + pairs = kwargs.items() validated = [] for prop, vals in pairs: @@ -825,7 +823,7 @@ def cycler(*args, **kwargs): def validate_cycler(s): 'return a Cycler object from a string repr or the object itself' - if isinstance(s, six.string_types): + if isinstance(s, str): try: # TODO: We might want to rethink this... # While I think I have it quite locked down, @@ -908,7 +906,7 @@ def validate_animation_writer_path(p): # Make sure it's a string and then figure out if the animations # are already loaded and reset the writers (which will validate # the path on next call) - if not isinstance(p, six.string_types): + if not isinstance(p, str): raise ValueError("path must be a (unicode) string") from sys import modules # set dirty, so that the next call to the registry will re-evaluate diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index c3536f02efe0..7c090555bde2 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -134,9 +134,6 @@ plot_template Provide a customized template for preparing restructured text. """ -import six -from six.moves import xrange - import itertools import sys, os, shutil, io, re, textwrap from os.path import relpath @@ -144,9 +141,6 @@ import traceback import warnings -if not six.PY3: - import cStringIO - from docutils.parsers.rst import directives from docutils.parsers.rst.directives.images import Image align = Image.align @@ -221,7 +215,7 @@ def mark_plot_labels(app, document): the "htmlonly" (or "latexonly") node to the actual figure node itself. """ - for name, explicit in six.iteritems(document.nametypes): + for name, explicit in document.nametypes.items(): if not explicit: continue labelid = document.nameids[name] @@ -466,10 +460,7 @@ def run_code(code, code_path, ns=None, function_name=None): # Change the working directory to the directory of the example, so # it can get at its data files, if any. Add its path to sys.path # so it can import any helper modules sitting beside it. - if six.PY2: - pwd = os.getcwdu() - else: - pwd = os.getcwd() + pwd = os.getcwd() old_sys_path = list(sys.path) if setup.config.plot_working_directory is not None: try: @@ -494,10 +485,7 @@ def run_code(code, code_path, ns=None, function_name=None): # Redirect stdout stdout = sys.stdout - if six.PY3: - sys.stdout = io.StringIO() - else: - sys.stdout = cStringIO.StringIO() + sys.stdout = io.StringIO() # Assign a do-nothing print function to the namespace. There # doesn't seem to be any other way to provide a way to (not) print @@ -512,17 +500,16 @@ def _dummy_print(*arg, **kwarg): ns = {} if not ns: if setup.config.plot_pre_code is None: - six.exec_(six.text_type("import numpy as np\n" + - "from matplotlib import pyplot as plt\n"), ns) + exec('import numpy as np\n' + 'from matplotlib import pyplot as plt\n', ns) else: - six.exec_(six.text_type(setup.config.plot_pre_code), ns) + exec(str(setup.config.plot_pre_code), ns) ns['print'] = _dummy_print if "__main__" in code: - six.exec_("__name__ = '__main__'", ns) - code = remove_coding(code) - six.exec_(code, ns) + exec("__name__ = '__main__'", ns) + exec(code, ns) if function_name is not None: - six.exec_(function_name + "()", ns) + exec(function_name + "()", ns) except (Exception, SystemExit) as err: raise PlotError(traceback.format_exc()) finally: @@ -544,13 +531,13 @@ def get_plot_formats(config): default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200} formats = [] plot_formats = config.plot_formats - if isinstance(plot_formats, six.string_types): + if isinstance(plot_formats, str): # String Sphinx < 1.3, Split on , to mimic # Sphinx 1.3 and later. Sphinx 1.3 always # returns a list. plot_formats = plot_formats.split(',') for fmt in plot_formats: - if isinstance(fmt, six.string_types): + if isinstance(fmt, str): if ':' in fmt: suffix, dpi = fmt.split(':') formats.append((str(suffix), int(dpi))) @@ -701,7 +688,7 @@ def run(arguments, content, options, state_machine, state, lineno): output_base = os.path.basename(source_file_name) else: source_file_name = rst_file - code = textwrap.dedent("\n".join(map(six.text_type, content))) + code = textwrap.dedent("\n".join(map(str, content))) counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter base, ext = os.path.splitext(os.path.basename(source_file_name)) @@ -805,7 +792,7 @@ def run(arguments, content, options, state_machine, state, lineno): images = [] opts = [ - ':%s: %s' % (key, val) for key, val in six.iteritems(options) + ':%s: %s' % (key, val) for key, val in options.items() if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] only_html = ".. only:: html" diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 4e4a332682ee..bd6961b16d75 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -1,4 +1,3 @@ -import six from itertools import chain, product from distutils.version import LooseVersion import io @@ -746,8 +745,7 @@ def test_polar_rlabel_position(): ax.tick_params(rotation='auto') -@image_comparison(baseline_images=['polar_theta_wedge'], style='default', - tol=0.01 if six.PY2 else 0) +@image_comparison(baseline_images=['polar_theta_wedge'], style='default') def test_polar_theta_limits(): r = np.arange(0, 3.0, 0.01) theta = 2*np.pi*r @@ -4370,7 +4368,7 @@ def test_twin_spines(): def make_patch_spines_invisible(ax): ax.set_frame_on(True) ax.patch.set_visible(False) - for sp in six.itervalues(ax.spines): + for sp in ax.spines.values(): sp.set_visible(False) fig = plt.figure(figsize=(4, 3)) diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py index 2a5f7247dfa5..25b98754a007 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -1,4 +1,3 @@ -import six import sys import matplotlib @@ -22,14 +21,7 @@ def test_override_builtins(): 'sum', 'divmod' } - - # We could use six.moves.builtins here, but that seems - # to do a little more than just this. - if six.PY3: - builtins = sys.modules['builtins'] - else: - builtins = sys.modules['__builtin__'] - + builtins = sys.modules['builtins'] overridden = False for key in dir(pylab): if key in dir(builtins): diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 6ca863a7f1db..78febfbc2d0d 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -1,5 +1,4 @@ import copy -import six import itertools import warnings @@ -103,7 +102,7 @@ def test_BoundaryNorm(): expected = [-1, 0, 1, 2] for v, ex in zip(vals, expected): ret = bn(v) - assert isinstance(ret, six.integer_types) + assert isinstance(ret, int) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) @@ -112,7 +111,7 @@ def test_BoundaryNorm(): expected = [-1, 0, 2, 3] for v, ex in zip(vals, expected): ret = bn(v) - assert isinstance(ret, six.integer_types) + assert isinstance(ret, int) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) @@ -121,7 +120,7 @@ def test_BoundaryNorm(): expected = [0, 0, 2, 2] for v, ex in zip(vals, expected): ret = bn(v) - assert isinstance(ret, six.integer_types) + assert isinstance(ret, int) assert_array_equal(ret, ex) assert_array_equal(bn([v]), ex) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 69a2c39bdfeb..d336fea01ff7 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -1,5 +1,3 @@ -import six - import tempfile import warnings @@ -210,11 +208,7 @@ def test_stride_ensure_integer_type(self): @pytest.fixture def tempcsv(): - if six.PY2: - fd = tempfile.TemporaryFile(suffix='csv', mode="wb+") - else: - fd = tempfile.TemporaryFile(suffix='csv', mode="w+", newline='') - with fd: + with tempfile.TemporaryFile(suffix='csv', mode="w+", newline='') as fd: yield fd diff --git a/lib/matplotlib/tests/test_patches.py b/lib/matplotlib/tests/test_patches.py index 54bcbd5ddc31..da880df39874 100644 --- a/lib/matplotlib/tests/test_patches.py +++ b/lib/matplotlib/tests/test_patches.py @@ -1,8 +1,6 @@ """ Tests specific to the patches module. """ -import six - import numpy as np from numpy.testing import assert_almost_equal, assert_array_equal import pytest @@ -255,10 +253,10 @@ def test_wedge_movement(): 'theta1': (0, 30, 'set_theta1'), 'theta2': (45, 50, 'set_theta2')} - init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict)) + init_args = dict((k, v[0]) for (k, v) in param_dict.items()) w = mpatches.Wedge(**init_args) - for attr, (old_v, new_v, func) in six.iteritems(param_dict): + for attr, (old_v, new_v, func) in param_dict.items(): assert getattr(w, attr) == old_v getattr(w, func)(new_v) assert getattr(w, attr) == new_v diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index 14b589780c0a..23ba02a5720c 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -1,5 +1,3 @@ -import six - from collections import OrderedDict import os from unittest import mock @@ -400,10 +398,7 @@ def generate_validator_testcases(valid): } # Add some cases of bytes arguments that Python 2 can convert silently: ls_bytes_args = (b'dotted', 'dotted'.encode('ascii')) - if six.PY3: - ls_test['fail'] += tuple((arg, ValueError) for arg in ls_bytes_args) - else: - ls_test['success'] += tuple((arg, 'dotted') for arg in ls_bytes_args) + ls_test['fail'] += tuple((arg, ValueError) for arg in ls_bytes_args) # Update the validation test sequence. validation_tests += (ls_test,) diff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py index 290f51f91c54..9ce753349ccd 100644 --- a/lib/matplotlib/tests/test_style.py +++ b/lib/matplotlib/tests/test_style.py @@ -12,8 +12,6 @@ from matplotlib import pyplot as plt, style from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION -import six - PARAM = 'image.cmap' VALUE = 'pink' DUMMY_SETTINGS = {PARAM: VALUE} @@ -29,7 +27,7 @@ def temp_style(style_name, settings=None): # Write style settings to file in the temp directory. tempdir = tempfile.mkdtemp() with open(os.path.join(tempdir, temp_file), 'w') as f: - for k, v in six.iteritems(settings): + for k, v in settings.items(): f.write('%s: %s' % (k, v)) # Add temp directory to style path and reload so we can access this style. diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 1d98f19f5b89..a7b3e6044e1d 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -202,7 +202,7 @@ def _divmod(x, y): x = x.item() if isinstance(y, np.generic): y = y.item() - return six.moves.builtins.divmod(x, y) + return divmod(x, y) def _mathdefault(s): @@ -1099,7 +1099,7 @@ def __call__(self, x, pos=None): exponent = np.round(fx) if is_x_decade else np.floor(fx) coeff = np.round(x / b ** exponent) if is_x_decade: - fx = nearest_long(fx) + fx = round(fx) if self.labelOnlyBase and not is_x_decade: return '' @@ -1120,15 +1120,10 @@ def __call__(self, x, pos=None): '{0}{1:g}'.format(sign_string, x))) elif not is_x_decade: return self._non_decade_format(sign_string, base, fx, usetex) + elif usetex: + return r'$%s%s^{%d}$' % (sign_string, base, fx) else: - if usetex: - return (r'$%s%s^{%d}$') % (sign_string, - base, - nearest_long(fx)) - else: - return ('$%s$' % _mathdefault( - '%s%s^{%d}' % - (sign_string, base, nearest_long(fx)))) + return '$%s$' % _mathdefault('%s%s^{%d}' % (sign_string, base, fx)) class LogFormatterSciNotation(LogFormatterMathtext): @@ -1142,7 +1137,7 @@ def _non_decade_format(self, sign_string, base, fx, usetex): exponent = math.floor(fx) coeff = b ** fx / b ** exponent if is_close_to_int(coeff): - coeff = nearest_long(coeff) + coeff = round(coeff) if usetex: return (r'$%s%g\times%s^{%d}$') % \ (sign_string, coeff, base, exponent) @@ -2003,7 +1998,7 @@ def is_decade(x, base=10): def is_close_to_int(x): if not np.isfinite(x): return False - return abs(x - nearest_long(x)) < 1e-10 + return abs(x - round(x)) < 1e-10 class LogLocator(Locator): @@ -2066,7 +2061,7 @@ def subs(self, subs): """ if subs is None: # consistency with previous bad API self._subs = 'auto' - elif isinstance(subs, six.string_types): + elif isinstance(subs, str): if subs not in ('all', 'auto'): raise ValueError("A subs string must be 'all' or 'auto'; " "found '%s'." % subs) @@ -2115,7 +2110,7 @@ def tick_values(self, vmin, vmax): numdec = math.floor(vmax) - math.ceil(vmin) - if isinstance(self._subs, six.string_types): + if isinstance(self._subs, str): _first = 2.0 if self._subs == 'auto' else 1.0 if numdec > 10 or b < 3: if self._subs == 'auto': diff --git a/lib/matplotlib/type1font.py b/lib/matplotlib/type1font.py index 50ec25f68277..409f22aab144 100644 --- a/lib/matplotlib/type1font.py +++ b/lib/matplotlib/type1font.py @@ -22,8 +22,6 @@ v1.1, 1993. ISBN 0-201-57044-0. """ -import six - import binascii import enum import itertools @@ -32,10 +30,6 @@ import numpy as np -if six.PY3: - def ord(x): - return x - # token types _TokenType = enum.Enum('_TokenType', @@ -84,8 +78,8 @@ def _read(self, file): while rawdata: if not rawdata.startswith(b'\x80'): raise RuntimeError('Broken pfb file (expected byte 128, ' - 'got %d)' % ord(rawdata[0])) - type = ord(rawdata[1]) + 'got %d)' % rawdata[0]) + type = rawdata[1] if type in (1, 2): length, = struct.unpack(str(' Date: Fri, 11 May 2018 23:37:20 +1000 Subject: [PATCH 3/5] Deprecate now-useless functions --- lib/matplotlib/sphinxext/plot_directive.py | 1 + lib/matplotlib/ticker.py | 17 +++++------------ 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index 7c090555bde2..9ca5f360af94 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -339,6 +339,7 @@ def remove_coding(text): r""" Remove the coding comment, which six.exec\_ doesn't like. """ + cbook.warn_deprecated('3.0', name='remove_coding', removal='3.1') sub_re = re.compile("^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE) return sub_re.sub("", text) diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index a7b3e6044e1d..3cd7559af9af 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -164,8 +164,6 @@ module for more information and examples of using date locators and formatters. """ -import six - import itertools import logging import locale @@ -192,10 +190,6 @@ 'SymmetricalLogLocator', 'LogitLocator') -if six.PY3: - long = int - - # Work around numpy/numpy#6127. def _divmod(x, y): if isinstance(x, np.generic): @@ -1978,12 +1972,11 @@ def decade_up(x, base=10): def nearest_long(x): - if x == 0: - return long(0) - elif x > 0: - return long(x + 0.5) - else: - return long(x - 0.5) + cbook.warn_deprecated('3.0', removal='3.1', name='`nearest_long`', + obj_type='function', alternative='`round`') + if x >= 0: + return int(x + 0.5) + return int(x - 0.5) def is_decade(x, base=10): From 22ff3e2f5859ae5a05a852e825e3228d60233b8a Mon Sep 17 00:00:00 2001 From: Zac-HD Date: Fri, 11 May 2018 23:37:50 +1000 Subject: [PATCH 4/5] Do not install `six` on py3-only version --- INSTALL.rst | 1 - setupext.py | 1 - 2 files changed, 2 deletions(-) diff --git a/INSTALL.rst b/INSTALL.rst index bb2402ede7da..d35fc07aa654 100644 --- a/INSTALL.rst +++ b/INSTALL.rst @@ -142,7 +142,6 @@ Matplotlib requires the following dependencies: * `pytz `__ * FreeType (>= 2.3) * `cycler `__ (>= 0.10.0) - * `six `_ (>= 1.10) * `kiwisolver `__ (>= 1.0.0) Optionally, you can also install a number of packages to enable better user diff --git a/setupext.py b/setupext.py index 0180f0eb8df0..b87741f9dce5 100644 --- a/setupext.py +++ b/setupext.py @@ -1340,7 +1340,6 @@ def get_install_requires(self): "pyparsing>=2.0.1,!=2.0.4,!=2.1.2,!=2.1.6", "python-dateutil>=2.1", "pytz", - "six>=1.10", ] From 17f06ee14f5466033227c43c5541cf8af8b673cd Mon Sep 17 00:00:00 2001 From: Zac-HD Date: Sat, 12 May 2018 11:35:29 +1000 Subject: [PATCH 5/5] Final edits for anntzer's review --- lib/matplotlib/patches.py | 6 +++--- lib/matplotlib/sphinxext/plot_directive.py | 4 ++-- lib/matplotlib/tests/test_basic.py | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 6361451d6d83..c77a825baca0 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1847,9 +1847,9 @@ def _pprint_styles(_styles): for name, cls in sorted(_styles.items()): spec = inspect.getfullargspec(cls.__init__) if spec.defaults: - argstr = ",".join("%s=%s" % pair - for pair in zip(spec.args[-len(spec.defaults):], - spec.defaults)) + argstr = ", ".join(map( + "{}={}".format, spec.args[-len(spec.defaults):], spec.defaults + )) else: argstr = 'None' # adding ``quotes`` since - and | have special meaning in reST diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index 9ca5f360af94..eae97820bf6e 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -462,7 +462,7 @@ def run_code(code, code_path, ns=None, function_name=None): # it can get at its data files, if any. Add its path to sys.path # so it can import any helper modules sitting beside it. pwd = os.getcwd() - old_sys_path = list(sys.path) + old_sys_path = sys.path.copy() if setup.config.plot_working_directory is not None: try: os.chdir(setup.config.plot_working_directory) @@ -507,7 +507,7 @@ def _dummy_print(*arg, **kwarg): exec(str(setup.config.plot_pre_code), ns) ns['print'] = _dummy_print if "__main__" in code: - exec("__name__ = '__main__'", ns) + ns['__name__'] = '__main__' exec(code, ns) if function_name is not None: exec(function_name + "()", ns) diff --git a/lib/matplotlib/tests/test_basic.py b/lib/matplotlib/tests/test_basic.py index 25b98754a007..dee7f640c97f 100644 --- a/lib/matplotlib/tests/test_basic.py +++ b/lib/matplotlib/tests/test_basic.py @@ -1,4 +1,4 @@ -import sys +import builtins import matplotlib @@ -21,7 +21,6 @@ def test_override_builtins(): 'sum', 'divmod' } - builtins = sys.modules['builtins'] overridden = False for key in dir(pylab): if key in dir(builtins):