From 4930fbc5f7063621cea310192a550bf0c1cd5512 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sat, 18 May 2019 16:38:07 +0200 Subject: [PATCH] Remove APIs deprecated in mpl3.0. --- doc/api/artist_api.rst | 2 +- doc/api/next_api_changes/2019-05-18-AL.rst | 61 ++++++ doc/api/patches_api.rst | 1 - lib/matplotlib/__init__.py | 54 ------ lib/matplotlib/afm.py | 5 - lib/matplotlib/axes/_axes.py | 25 +-- lib/matplotlib/axes/_base.py | 5 - lib/matplotlib/backends/__init__.py | 51 ----- lib/matplotlib/backends/backend_cairo.py | 21 --- lib/matplotlib/backends/backend_gtk3.py | 4 - lib/matplotlib/backends/backend_pdf.py | 7 - lib/matplotlib/backends/backend_pgf.py | 8 - lib/matplotlib/backends/backend_ps.py | 49 ----- lib/matplotlib/backends/backend_qt5.py | 44 ----- lib/matplotlib/backends/backend_wx.py | 5 - lib/matplotlib/backends/tkagg.py | 47 ----- lib/matplotlib/backends/windowing.py | 37 ---- lib/matplotlib/backends/wx_compat.py | 36 ---- lib/matplotlib/cbook/__init__.py | 194 +------------------- lib/matplotlib/compat/subprocess.py | 42 ----- lib/matplotlib/container.py | 4 - lib/matplotlib/contour.py | 7 - lib/matplotlib/dates.py | 107 ----------- lib/matplotlib/font_manager.py | 48 ----- lib/matplotlib/markers.py | 48 ++--- lib/matplotlib/mathtext.py | 3 - lib/matplotlib/patches.py | 108 +---------- lib/matplotlib/pyplot.py | 12 +- lib/matplotlib/rcsetup.py | 3 - lib/matplotlib/sphinxext/plot_directive.py | 7 - lib/matplotlib/table.py | 1 - lib/matplotlib/testing/__init__.py | 8 - lib/matplotlib/testing/compare.py | 55 +----- lib/matplotlib/testing/decorators.py | 112 +---------- lib/matplotlib/tests/test_axes.py | 20 +- lib/matplotlib/tests/test_dates.py | 49 ----- lib/matplotlib/tests/test_mlab.py | 8 - lib/matplotlib/tests/test_patches.py | 4 - lib/matplotlib/tests/test_rcparams.py | 3 - lib/matplotlib/text.py | 6 - lib/matplotlib/textpath.py | 5 - lib/matplotlib/ticker.py | 55 ------ lib/mpl_toolkits/axes_grid/__init__.py | 3 +- lib/mpl_toolkits/axes_grid/axes_divider.py | 4 +- lib/mpl_toolkits/axes_grid/axes_grid.py | 1 - lib/mpl_toolkits/axes_grid1/__init__.py | 4 +- lib/mpl_toolkits/axes_grid1/axes_divider.py | 31 ---- lib/mpl_toolkits/axisartist/axes_divider.py | 19 +- src/_tkagg.cpp | 166 ----------------- 49 files changed, 114 insertions(+), 1485 deletions(-) create mode 100644 doc/api/next_api_changes/2019-05-18-AL.rst delete mode 100644 lib/matplotlib/backends/tkagg.py delete mode 100644 lib/matplotlib/backends/windowing.py delete mode 100644 lib/matplotlib/backends/wx_compat.py delete mode 100644 lib/matplotlib/compat/subprocess.py diff --git a/doc/api/artist_api.rst b/doc/api/artist_api.rst index 4ac1a42b1505..85e8edb76f2f 100644 --- a/doc/api/artist_api.rst +++ b/doc/api/artist_api.rst @@ -4,7 +4,7 @@ ``matplotlib.artist`` ********************* -.. inheritance-diagram:: matplotlib.axes._axes.Axes matplotlib.axes._base._AxesBase matplotlib.axis.Axis matplotlib.axis.Tick matplotlib.axis.XAxis matplotlib.axis.XTick matplotlib.axis.YAxis matplotlib.axis.YTick matplotlib.collections.AsteriskPolygonCollection matplotlib.collections.BrokenBarHCollection matplotlib.collections.CircleCollection matplotlib.collections.Collection matplotlib.collections.EllipseCollection matplotlib.collections.EventCollection matplotlib.collections.LineCollection matplotlib.collections.PatchCollection matplotlib.collections.PathCollection matplotlib.collections.PolyCollection matplotlib.collections.QuadMesh matplotlib.collections.RegularPolyCollection matplotlib.collections.StarPolygonCollection matplotlib.collections.TriMesh matplotlib.collections._CollectionWithSizes matplotlib.contour.ClabelText matplotlib.figure.Figure matplotlib.image.AxesImage matplotlib.image.BboxImage matplotlib.image.FigureImage matplotlib.image.NonUniformImage matplotlib.image.PcolorImage matplotlib.image._ImageBase matplotlib.legend.Legend matplotlib.lines.Line2D matplotlib.offsetbox.AnchoredOffsetbox matplotlib.offsetbox.AnchoredText matplotlib.offsetbox.AnnotationBbox matplotlib.offsetbox.AuxTransformBox matplotlib.offsetbox.DrawingArea matplotlib.offsetbox.HPacker matplotlib.offsetbox.OffsetBox matplotlib.offsetbox.OffsetImage matplotlib.offsetbox.PackerBase matplotlib.offsetbox.PaddedBox matplotlib.offsetbox.TextArea matplotlib.offsetbox.VPacker matplotlib.patches.Arc matplotlib.patches.Arrow matplotlib.patches.Circle matplotlib.patches.CirclePolygon matplotlib.patches.ConnectionPatch matplotlib.patches.Ellipse matplotlib.patches.FancyArrow matplotlib.patches.FancyArrowPatch matplotlib.patches.FancyBboxPatch matplotlib.patches.Patch matplotlib.patches.PathPatch matplotlib.patches.Polygon matplotlib.patches.Rectangle matplotlib.patches.RegularPolygon matplotlib.patches.Shadow matplotlib.patches.Wedge matplotlib.patches.YAArrow matplotlib.projections.geo.AitoffAxes matplotlib.projections.geo.GeoAxes matplotlib.projections.geo.HammerAxes matplotlib.projections.geo.LambertAxes matplotlib.projections.geo.MollweideAxes matplotlib.projections.polar.PolarAxes matplotlib.quiver.Barbs matplotlib.quiver.Quiver matplotlib.quiver.QuiverKey matplotlib.spines.Spine matplotlib.table.Cell matplotlib.table.CustomCell matplotlib.table.Table matplotlib.text.Annotation matplotlib.text.Text matplotlib.text.TextWithDash +.. inheritance-diagram:: matplotlib.axes._axes.Axes matplotlib.axes._base._AxesBase matplotlib.axis.Axis matplotlib.axis.Tick matplotlib.axis.XAxis matplotlib.axis.XTick matplotlib.axis.YAxis matplotlib.axis.YTick matplotlib.collections.AsteriskPolygonCollection matplotlib.collections.BrokenBarHCollection matplotlib.collections.CircleCollection matplotlib.collections.Collection matplotlib.collections.EllipseCollection matplotlib.collections.EventCollection matplotlib.collections.LineCollection matplotlib.collections.PatchCollection matplotlib.collections.PathCollection matplotlib.collections.PolyCollection matplotlib.collections.QuadMesh matplotlib.collections.RegularPolyCollection matplotlib.collections.StarPolygonCollection matplotlib.collections.TriMesh matplotlib.collections._CollectionWithSizes matplotlib.contour.ClabelText matplotlib.figure.Figure matplotlib.image.AxesImage matplotlib.image.BboxImage matplotlib.image.FigureImage matplotlib.image.NonUniformImage matplotlib.image.PcolorImage matplotlib.image._ImageBase matplotlib.legend.Legend matplotlib.lines.Line2D matplotlib.offsetbox.AnchoredOffsetbox matplotlib.offsetbox.AnchoredText matplotlib.offsetbox.AnnotationBbox matplotlib.offsetbox.AuxTransformBox matplotlib.offsetbox.DrawingArea matplotlib.offsetbox.HPacker matplotlib.offsetbox.OffsetBox matplotlib.offsetbox.OffsetImage matplotlib.offsetbox.PackerBase matplotlib.offsetbox.PaddedBox matplotlib.offsetbox.TextArea matplotlib.offsetbox.VPacker matplotlib.patches.Arc matplotlib.patches.Arrow matplotlib.patches.Circle matplotlib.patches.CirclePolygon matplotlib.patches.ConnectionPatch matplotlib.patches.Ellipse matplotlib.patches.FancyArrow matplotlib.patches.FancyArrowPatch matplotlib.patches.FancyBboxPatch matplotlib.patches.Patch matplotlib.patches.PathPatch matplotlib.patches.Polygon matplotlib.patches.Rectangle matplotlib.patches.RegularPolygon matplotlib.patches.Shadow matplotlib.patches.Wedge matplotlib.projections.geo.AitoffAxes matplotlib.projections.geo.GeoAxes matplotlib.projections.geo.HammerAxes matplotlib.projections.geo.LambertAxes matplotlib.projections.geo.MollweideAxes matplotlib.projections.polar.PolarAxes matplotlib.quiver.Barbs matplotlib.quiver.Quiver matplotlib.quiver.QuiverKey matplotlib.spines.Spine matplotlib.table.Cell matplotlib.table.CustomCell matplotlib.table.Table matplotlib.text.Annotation matplotlib.text.Text matplotlib.text.TextWithDash :parts: 1 :private-bases: diff --git a/doc/api/next_api_changes/2019-05-18-AL.rst b/doc/api/next_api_changes/2019-05-18-AL.rst new file mode 100644 index 000000000000..7c19834f6ddd --- /dev/null +++ b/doc/api/next_api_changes/2019-05-18-AL.rst @@ -0,0 +1,61 @@ +API removals +```````````` + +The following deprecated APIs were removed: + +- the ``matplotlib.backends.tkagg``, ``matplotlib.backends.windowing``, + ``matplotlib.backends.wx_compat``, and ``matplotlib.compat.subprocess`` + modules, +- ``RcParams.msg_depr``, ``RcParams.msg_depr_ignore``, + ``RcParams.msg_depr_set``, ``RcParams.msg_obsolete``, + ``RcParams.msg_backend_obsolete``, +- ``afm.parse_afm`` (use ``afm.AFM instead``), +- ``axes.Axes.mouseover_set``, +- ``backend_cairo.ArrayWrapper``, ``backend_cairo.RendererCairo.convert_path``, +- ``backend_gtk3.FileChooserDialog.sorted_filetypes`` (use + ``sorted(self.filetypes.items())`` instead), +- ``backend_pgf.get_texcommand``, +- ``backend_pdf.PdfFile.texFontMap``, +- ``backend_ps.get_bbox``, +- ``backend_qt.FigureCanvasQt.keyAutoRepeat`` (use + ``event.guiEvent.isAutoRepeat`` instead), ``backend_qt.error_msg_qt``, + ``backend_qt.exception_handler``, +- ``backend_wx.FigureCanvasWx.macros``, +- ``backends.pylab_setup``, +- ``cbook.Bunch`` (use ``types.SimpleNamespace`` instead), ``cbook.Locked``, + ``cbook.unicode_safe``, ``cbook.is_numlike`` (use + ``isinstance(..., numbers.Number)`` instead), ``cbook.mkdirs`` (use + ``os.makedirs(..., exist_ok=True)`` instead), ``cbook.GetRealpathAndStat`` + (use ``cbook.get_realpath_and_stat`` instead), + ``cbook.listFiles``, +- ``container.Container.set_remove_method``, +- ``contour.ContourLabeler.cl``, ``contour.ContourLabeler.cl_xy``, + ``contour.ContourLabeler.cl_cvalues`` (use ``labelTexts``, ``labelXYs``, + ``labelCValues`` instead), +- ``dates.DateFormatter.strftime``, ``dates.DateFormatter.strftime_pre_1900``, +- ``font_manager.TempCache``, ``font_manager.FontManager.ttffiles``, + ``font_manager.FontManager.afmfiles``, +- ``mathtext.unichr_safe`` (use ``chr`` instead), +- ``patches.YAArrow`` (use ``patches.FancyArrowPatch`` instead), +- ``sphinxext.plot_directive.remove_coding``, +- ``table.Table.get_child_artists``, +- ``testing.compare.compare_float``, ``testing.decorators.CleanupTest``, + ``testing.decorators.ImageComparisonTest``, + ``testing.decorators.skip_if_command_unavailable``, + support for nose-based tests, +- ``text.Annotation.arrow`` (use ``text.Annotation.arrow_patch`` instead), +- ``textpath.TextToPath.tex_font_map``, +- ``ticker.Base``, ``ticker.closeto``, ``ticker.nearest_long``, +- ``axes_grid1.axes_divider.LocatableAxesBase``, + ``axes_grid1.axes_divider.locatable_axes_factory``, + ``axes_grid1.axes_divider.Axes`` (use ``axes_grid1.mpl_axes.Axes`` instead), + ``axes_grid1.axes_divider.LocatableAxes`` (use ``axes_grid1.mpl_axes.Axes`` + instead), +- ``axisartist.axes_divider.Axes``, ``axisartist.axes_divider.LocatableAxes`` + (use ``axisartist.axislines.Axes`` instead), +- the ``normed`` kwarg to ``hist`` (use ``density`` instead), +- the ``verts`` parameter to ``scatter`` (use ``marker`` instead), +- passing ``(verts, 0)`` or ``(..., 3)`` when specifying a marker to specify a + path or a circle, respectively (instead, use ``verts`` or ``"o"``, + respectively), +- :rc:`examples.directory`, diff --git a/doc/api/patches_api.rst b/doc/api/patches_api.rst index 4fd59541d164..e183fde84c12 100644 --- a/doc/api/patches_api.rst +++ b/doc/api/patches_api.rst @@ -34,7 +34,6 @@ Classes RegularPolygon Shadow Wedge - YAArrow Functions --------- diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 1196af17b4ed..8ef01d7421c8 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -716,35 +716,6 @@ class RcParams(MutableMapping, dict): for key, (default, converter) in defaultParams.items() if key not in _all_deprecated} - @cbook.deprecated("3.0") - @property - def msg_depr(self): - return "%s is deprecated and replaced with %s; please use the latter." - - @cbook.deprecated("3.0") - @property - def msg_depr_ignore(self): - return "%s is deprecated and ignored. Use %s instead." - - @cbook.deprecated("3.0") - @property - def msg_depr_set(self): - return ("%s is deprecated. Please remove it from your matplotlibrc " - "and/or style files.") - - @cbook.deprecated("3.0") - @property - def msg_obsolete(self): - return ("%s is obsolete. Please remove it from your matplotlibrc " - "and/or style files.") - - @cbook.deprecated("3.0") - @property - def msg_backend_obsolete(self): - return ("The {} rcParam was deprecated in version 2.2. In order to " - "force the use of a specific Qt binding, either import that " - "binding first, or set the QT_API environment variable.") - # validate values on the way in def __init__(self, *args, **kwargs): self.update(*args, **kwargs) @@ -766,11 +737,6 @@ def __setitem__(self, key, val): cbook.warn_deprecated( version, name=key, obj_type="rcparam", alternative=alt_key) return - elif key == 'examples.directory': - cbook.warn_deprecated( - "3.0", name=key, obj_type="rcparam", addendum="In the " - "future, examples will be found relative to the " - "'datapath' directory.") elif key == 'backend': if val is rcsetup._auto_backend_sentinel: if 'backend' in self: @@ -798,11 +764,6 @@ def __getitem__(self, key): version, name=key, obj_type="rcparam", alternative=alt_key) return dict.__getitem__(self, alt_key) if alt_key else None - elif key == 'examples.directory': - cbook.warn_deprecated( - "3.0", name=key, obj_type="rcparam", addendum="In the future, " - "examples will be found relative to the 'datapath' directory.") - elif key == "backend": val = dict.__getitem__(self, key) if val is rcsetup._auto_backend_sentinel: @@ -990,21 +951,6 @@ def rc_params_from_file(fname, fail_on_error=False, use_default_template=True): # this is the instance used by the matplotlib classes rcParams = rc_params() -# Don't trigger deprecation warning when just fetching. -if dict.__getitem__(rcParams, 'examples.directory'): - # paths that are intended to be relative to matplotlib_fname() - # are allowed for the examples.directory parameter. - # However, we will need to fully qualify the path because - # Sphinx requires absolute paths. - if not os.path.isabs(rcParams['examples.directory']): - _basedir, _fname = os.path.split(matplotlib_fname()) - # Sometimes matplotlib_fname() can return relative paths, - # Also, using realpath() guarantees that Sphinx will use - # the same path that matplotlib sees (in case of weird symlinks). - _basedir = os.path.realpath(_basedir) - _fullpath = os.path.join(_basedir, rcParams['examples.directory']) - rcParams['examples.directory'] = _fullpath - with cbook._suppress_matplotlib_deprecation_warning(): rcParamsOrig = RcParams(rcParams.copy()) diff --git a/lib/matplotlib/afm.py b/lib/matplotlib/afm.py index c2b0090adbcd..021084bac06c 100644 --- a/lib/matplotlib/afm.py +++ b/lib/matplotlib/afm.py @@ -368,11 +368,6 @@ def _parse_optional(fh): return d[b'StartKernData'], d[b'StartComposites'] -@deprecated("3.0", alternative="the AFM class") -def parse_afm(fh): - return _parse_afm(fh) - - def _parse_afm(fh): """ Parse the Adobe Font Metrics file in file handle *fh*. diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 2bae8ff07a0a..67c3d51cb351 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -4313,6 +4313,7 @@ def _parse_scatter_color_args(c, edgecolors, kwargs, xsize, "edgecolors", "c", "facecolor", "facecolors", "color"], label_namer="y") + @cbook._delete_parameter("3.2", "verts") def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, plotnonfinite=False, @@ -4465,13 +4466,6 @@ def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None, scales = s # Renamed for readability below. - # to be API compatible - if verts is not None: - cbook.warn_deprecated("3.0", name="'verts'", obj_type="kwarg", - alternative="'marker'") - if marker is None: - marker = verts - # load default marker from rcParams if marker is None: marker = rcParams['scatter.marker'] @@ -6394,8 +6388,7 @@ def clabel(self, CS, *args, **kwargs): def hist(self, x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, - color=None, label=None, stacked=False, normed=None, - **kwargs): + color=None, label=None, stacked=False, **kwargs): """ Plot a histogram. @@ -6576,9 +6569,6 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, Default is ``False`` - normed : bool, optional - Deprecated; use the density keyword argument instead. - Returns ------- n : array or list of arrays @@ -6628,15 +6618,6 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, if histtype == 'barstacked' and not stacked: stacked = True - if density is not None and normed is not None: - raise ValueError("kwargs 'density' and 'normed' cannot be used " - "simultaneously. " - "Please only use 'density', since 'normed'" - "is deprecated.") - if normed is not None: - cbook.warn_deprecated("2.1", name="'normed'", obj_type="kwarg", - alternative="'density'", removal="3.1") - # basic input validation input_empty = np.size(x) == 0 # Massage 'x' for processing. @@ -6708,7 +6689,7 @@ def hist(self, x, bins=None, range=None, density=None, weights=None, else: hist_kwargs['range'] = bin_range - density = bool(density) or bool(normed) + density = bool(density) if density and not stacked: hist_kwargs['density'] = density diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 93bd354cd1e6..88b57bf4ae55 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1124,11 +1124,6 @@ def cla(self): self.stale = True - @cbook.deprecated("3.0") - @property - def mouseover_set(self): - return frozenset(self._mouseover_set) - def clear(self): """Clear the axes.""" self.cla() diff --git a/lib/matplotlib/backends/__init__.py b/lib/matplotlib/backends/__init__.py index 9d8a74fb8c74..e00942f0ce9f 100644 --- a/lib/matplotlib/backends/__init__.py +++ b/lib/matplotlib/backends/__init__.py @@ -52,54 +52,3 @@ def _get_running_interactive_framework(): if sys.platform.startswith("linux") and not os.environ.get("DISPLAY"): return "headless" return None - - -@cbook.deprecated("3.0") -def pylab_setup(name=None): - """ - Return new_figure_manager, draw_if_interactive and show for pyplot. - - This provides the backend-specific functions that are used by pyplot to - abstract away the difference between backends. - - Parameters - ---------- - name : str, optional - The name of the backend to use. If `None`, falls back to - ``matplotlib.get_backend()`` (which return :rc:`backend`). - - Returns - ------- - backend_mod : module - The module which contains the backend of choice - - new_figure_manager : function - Create a new figure manager (roughly maps to GUI window) - - draw_if_interactive : function - Redraw the current figure if pyplot is interactive - - show : function - Show (and possibly block) any unshown figures. - """ - # Import the requested backend into a generic module object. - if name is None: - name = matplotlib.get_backend() - backend_name = (name[9:] if name.startswith("module://") - else "matplotlib.backends.backend_{}".format(name.lower())) - backend_mod = importlib.import_module(backend_name) - # Create a local Backend class whose body corresponds to the contents of - # the backend module. This allows the Backend class to fill in the missing - # methods through inheritance. - Backend = type("Backend", (_Backend,), vars(backend_mod)) - - # Need to keep a global reference to the backend for compatibility reasons. - # See https://github.com/matplotlib/matplotlib/issues/6092 - global backend - backend = name - - _log.debug('backend %s version %s', name, Backend.backend_version) - return (backend_mod, - Backend.new_figure_manager, - Backend.draw_if_interactive, - Backend.show) diff --git a/lib/matplotlib/backends/backend_cairo.py b/lib/matplotlib/backends/backend_cairo.py index 89b594f1aeb1..270ba252ae25 100644 --- a/lib/matplotlib/backends/backend_cairo.py +++ b/lib/matplotlib/backends/backend_cairo.py @@ -51,22 +51,6 @@ def _to_context(ctx): return ctx -@cbook.deprecated("3.0") -class ArrayWrapper: - """Thin wrapper around numpy ndarray to expose the interface - expected by cairocffi. Basically replicates the - array.array interface. - """ - def __init__(self, myarray): - self.__array = myarray - self.__data = myarray.ctypes.data - self.__size = len(myarray.flatten()) - self.itemsize = myarray.itemsize - - def buffer_info(self): - return (self.__data, self.__size) - - def _append_path(ctx, path, transform, clip=None): for points, code in path.iter_segments( transform, remove_nans=True, clip=clip): @@ -143,11 +127,6 @@ def _fill_and_stroke(self, ctx, fill_c, alpha, alpha_overrides): ctx.restore() ctx.stroke() - @staticmethod - @cbook.deprecated("3.0") - def convert_path(ctx, path, transform, clip=None): - _append_path(ctx, path, transform, clip) - def draw_path(self, gc, path, transform, rgbFace=None): # docstring inherited ctx = gc.ctx diff --git a/lib/matplotlib/backends/backend_gtk3.py b/lib/matplotlib/backends/backend_gtk3.py index 9153240d2eb4..a7628a5e56f6 100644 --- a/lib/matplotlib/backends/backend_gtk3.py +++ b/lib/matplotlib/backends/backend_gtk3.py @@ -682,10 +682,6 @@ def cb_cbox_changed(cbox, data=None): hbox.show_all() self.set_extra_widget(hbox) - @cbook.deprecated("3.0", alternative="sorted(self.filetypes.items())") - def sorted_filetypes(self): - return sorted(self.filetypes.items()) - def get_filename_from_user(self): if self.run() == int(Gtk.ResponseType.OK): return self.get_filename(), self.ext diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 082aa9a03181..ec749e7f5df8 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -651,13 +651,6 @@ def fontName(self, fontprop): return Fx - @cbook.deprecated("3.0") - @property - def texFontMap(self): - # lazy-load texFontMap, it takes a while to parse - # and usetex is a relatively rare use case - return dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) - def dviFontName(self, dvifont): """ Given a dvi font object, return a name suitable for Op.selectfont. diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index 3613fc67c9d2..06fbce63e39a 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -28,14 +28,6 @@ ############################################################################### -@cbook.deprecated("3.0") -def get_texcommand(): - """Get chosen TeX system from rc.""" - texsystem_options = ["xelatex", "lualatex", "pdflatex"] - texsystem = rcParams["pgf.texsystem"] - return texsystem if texsystem in texsystem_options else "xelatex" - - def get_fontspec(): """Build fontspec preamble from rc.""" latex_fontspec = [] diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index d4340335762c..56e67b47806e 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1450,55 +1450,6 @@ def get_bbox_header(lbrt, rotated=False): return '\n'.join([bbox_info, hires_bbox_info]), rotate -# get_bbox is deprecated. I don't see any reason to use ghostscript to -# find the bounding box, as the required bounding box is alread known. -@cbook.deprecated("3.0") -def get_bbox(tmpfile, bbox): - """ - Use ghostscript's bbox device to find the center of the bounding box. - Return an appropriately sized bbox centered around that point. A bit of a - hack. - """ - - gs_exe = ps_backend_helper.gs_exe - command = [gs_exe, "-dBATCH", "-dNOPAUSE", "-sDEVICE=bbox", "%s" % tmpfile] - _log.debug(command) - p = subprocess.Popen(command, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - close_fds=True) - (stdout, stderr) = (p.stdout, p.stderr) - _log.debug(stdout.read()) - bbox_info = stderr.read() - _log.info(bbox_info) - bbox_found = re.search('%%HiResBoundingBox: .*', bbox_info) - if bbox_found: - bbox_info = bbox_found.group() - else: - raise RuntimeError( - 'Ghostscript was not able to extract a bounding box.' - 'Here is the Ghostscript output:\n\n%s' % bbox_info) - l, b, r, t = [float(i) for i in bbox_info.split()[-4:]] - - # this is a hack to deal with the fact that ghostscript does not return the - # intended bbox, but a tight bbox. For now, we just center the ink in the - # intended bbox. This is not ideal, users may intend the ink to not be - # centered. - if bbox is None: - l, b, r, t = (l-1, b-1, r+1, t+1) - else: - x = (l+r)/2 - y = (b+t)/2 - dx = (bbox[2]-bbox[0])/2 - dy = (bbox[3]-bbox[1])/2 - l, b, r, t = (x-dx, y-dy, x+dx, y+dy) - - bbox_info = '%%%%BoundingBox: %d %d %d %d' % (l, b, np.ceil(r), np.ceil(t)) - hires_bbox_info = '%%%%HiResBoundingBox: %.6f %.6f %.6f %.6f' % ( - l, b, r, t) - - return '\n'.join([bbox_info, hires_bbox_info]) - - def pstoeps(tmpfile, bbox=None, rotated=False): """ Convert the postscript to encapsulated postscript. The bbox of diff --git a/lib/matplotlib/backends/backend_qt5.py b/lib/matplotlib/backends/backend_qt5.py index 8a0ccbf470da..22e97bbbb393 100644 --- a/lib/matplotlib/backends/backend_qt5.py +++ b/lib/matplotlib/backends/backend_qt5.py @@ -246,8 +246,6 @@ def __init__(self, figure): self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) self.setMouseTracking(True) self.resize(*self.get_width_height()) - # Key auto-repeat enabled by default - self._keyautorepeat = True palette = QtGui.QPalette(QtCore.Qt.white) self.setPalette(palette) @@ -375,18 +373,6 @@ def keyReleaseEvent(self, event): if key is not None: FigureCanvasBase.key_release_event(self, key, guiEvent=event) - @cbook.deprecated("3.0", alternative="event.guiEvent.isAutoRepeat") - @property - def keyAutoRepeat(self): - """ - If True, enable auto-repeat for key events. - """ - return self._keyautorepeat - - @keyAutoRepeat.setter - def keyAutoRepeat(self, val): - self._keyautorepeat = bool(val) - def resizeEvent(self, event): # _dpi_ratio_prev will be set the first time the canvas is painted, and # the rendered buffer is useless before anyways. @@ -411,9 +397,6 @@ def minumumSizeHint(self): return QtCore.QSize(10, 10) def _get_key(self, event): - if not self._keyautorepeat and event.isAutoRepeat(): - return None - event_key = event.key() event_mods = int(event.modifiers()) # actually a bitmask @@ -1044,33 +1027,6 @@ def trigger(self, *args, **kwargs): backend_tools.ToolCopyToClipboard = ToolCopyToClipboardQT -@cbook.deprecated("3.0") -def error_msg_qt(msg, parent=None): - if not isinstance(msg, str): - msg = ','.join(map(str, msg)) - - QtWidgets.QMessageBox.warning(None, "Matplotlib", - msg, QtGui.QMessageBox.Ok) - - -@cbook.deprecated("3.0") -def exception_handler(type, value, tb): - """Handle uncaught exceptions - It does not catch SystemExit - """ - msg = '' - # get the filename attribute if available (for IOError) - if hasattr(value, 'filename') and value.filename is not None: - msg = value.filename + ': ' - if hasattr(value, 'strerror') and value.strerror is not None: - msg += value.strerror - else: - msg += str(value) - - if len(msg): - error_msg_qt(msg) - - @_Backend.export class _BackendQT5(_Backend): required_interactive_framework = "qt5" diff --git a/lib/matplotlib/backends/backend_wx.py b/lib/matplotlib/backends/backend_wx.py index 30a1860932b0..27202e380401 100644 --- a/lib/matplotlib/backends/backend_wx.py +++ b/lib/matplotlib/backends/backend_wx.py @@ -628,11 +628,6 @@ def __init__(self, parent, id, figure): self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Reduce flicker. self.SetBackgroundColour(wx.WHITE) - @property - @cbook.deprecated("3.0") - def macros(self): - return {} - def Copy_to_Clipboard(self, event=None): "copy bitmap of canvas to system clipboard" bmp_obj = wx.BitmapDataObject() diff --git a/lib/matplotlib/backends/tkagg.py b/lib/matplotlib/backends/tkagg.py deleted file mode 100644 index 476b1336c3a5..000000000000 --- a/lib/matplotlib/backends/tkagg.py +++ /dev/null @@ -1,47 +0,0 @@ -import tkinter as tk - -import numpy as np - -from matplotlib import cbook -from matplotlib.backends import _tkagg - - -cbook.warn_deprecated("3.0", name=__name__, obj_type="module") - - -def blit(photoimage, aggimage, bbox=None, colormode=1): - tk = photoimage.tk - - if bbox is not None: - bbox_array = bbox.__array__() - # x1, x2, y1, y2 - bboxptr = (bbox_array[0, 0], bbox_array[1, 0], - bbox_array[0, 1], bbox_array[1, 1]) - else: - bboxptr = 0 - data = np.asarray(aggimage) - dataptr = (data.shape[0], data.shape[1], data.ctypes.data) - try: - tk.call( - "PyAggImagePhoto", photoimage, - dataptr, colormode, bboxptr) - except tk.TclError: - if hasattr(tk, 'interpaddr'): - _tkagg.tkinit(tk.interpaddr(), 1) - else: - # very old python? - _tkagg.tkinit(tk, 0) - tk.call("PyAggImagePhoto", photoimage, - dataptr, colormode, bboxptr) - - -def test(aggimage): - r = tk.Tk() - c = tk.Canvas(r, width=aggimage.width, height=aggimage.height) - c.pack() - p = tk.PhotoImage(width=aggimage.width, height=aggimage.height) - blit(p, aggimage) - c.create_image(aggimage.width, aggimage.height, image=p) - blit(p, aggimage) - while True: - r.update_idletasks() diff --git a/lib/matplotlib/backends/windowing.py b/lib/matplotlib/backends/windowing.py deleted file mode 100644 index 8e93858d6749..000000000000 --- a/lib/matplotlib/backends/windowing.py +++ /dev/null @@ -1,37 +0,0 @@ -""" -MS Windows-specific helper for the TkAgg backend. - -With rcParams['tk.window_focus'] default of False, it is -effectively disabled. - -It uses a tiny C++ extension module to access MS Win functions. - -This module is deprecated and will be removed in version 3.2 -""" - -from matplotlib import rcParams, cbook - -cbook.warn_deprecated('3.0', obj_type='module', name='backends.windowing') - -try: - if not rcParams['tk.window_focus']: - raise ImportError - from matplotlib.backends._tkagg import ( - Win32_GetForegroundWindow as GetForegroundWindow, - Win32_SetForegroundWindow as SetForegroundWindow) - -except ImportError: - - def GetForegroundWindow(): - return 0 - - def SetForegroundWindow(hwnd): - pass - - -class FocusManager(object): - def __init__(self): - self._shellWindow = GetForegroundWindow() - - def __del__(self): - SetForegroundWindow(self._shellWindow) diff --git a/lib/matplotlib/backends/wx_compat.py b/lib/matplotlib/backends/wx_compat.py deleted file mode 100644 index 0b3d21d56b6b..000000000000 --- a/lib/matplotlib/backends/wx_compat.py +++ /dev/null @@ -1,36 +0,0 @@ -""" -A wx API adapter to hide differences between wxPython classic and phoenix. - -It is assumed that the user code is selecting what version it wants to use, -here we just ensure that it meets the minimum required by matplotlib. - -For an example see embedding_in_wx2.py -""" -import wx - -from .. import cbook -from .backend_wx import RendererWx - - -cbook.warn_deprecated("3.0", name=__name__, obj_type="module") - -backend_version = wx.VERSION_STRING -is_phoenix = 'phoenix' in wx.PlatformInfo - -fontweights = RendererWx.fontweights -fontangles = RendererWx.fontangles -fontnames = RendererWx.fontnames - -dashd_wx = {'solid': wx.PENSTYLE_SOLID, - 'dashed': wx.PENSTYLE_SHORT_DASH, - 'dashdot': wx.PENSTYLE_DOT_DASH, - 'dotted': wx.PENSTYLE_DOT} - -# functions changes -BitmapFromBuffer = wx.Bitmap.FromBufferRGBA -EmptyBitmap = wx.Bitmap -EmptyImage = wx.Image -Cursor = wx.Cursor -EventLoop = wx.GUIEventLoop -NamedColour = wx.Colour -StockCursor = wx.Cursor diff --git a/lib/matplotlib/cbook/__init__.py b/lib/matplotlib/cbook/__init__.py index 93e4243dd7ab..cfb91c13fcc1 100644 --- a/lib/matplotlib/cbook/__init__.py +++ b/lib/matplotlib/cbook/__init__.py @@ -39,32 +39,6 @@ MatplotlibDeprecationWarning, mplDeprecation) -@deprecated("3.0") -def unicode_safe(s): - - if isinstance(s, bytes): - try: - # On some systems, locale.getpreferredencoding returns None, - # which can break unicode; and the sage project reports that - # some systems have incorrect locale specifications, e.g., - # an encoding instead of a valid locale name. Another - # pathological case that has been reported is an empty string. - # On some systems, getpreferredencoding sets the locale, which has - # side effects. Passing False eliminates those side effects. - preferredencoding = locale.getpreferredencoding( - matplotlib.rcParams['axes.formatter.use_locale']).strip() - if not preferredencoding: - preferredencoding = None - except (ValueError, ImportError, AttributeError): - preferredencoding = None - - if preferredencoding is None: - return str(s) - else: - return str(s, preferredencoding) - return s - - def _exception_printer(exc): traceback.print_exc() @@ -328,20 +302,6 @@ def strip_math(s): return s -@deprecated('3.0', alternative='types.SimpleNamespace') -class Bunch(types.SimpleNamespace): - """ - Often we want to just collect a bunch of stuff together, naming each - item of the bunch; a dictionary's OK for that, but a small do- nothing - class is even handier, and prettier to use. Whenever you want to - group a few variables:: - - >>> point = Bunch(datum=2, squared=4, coord=12) - >>> point.datum - """ - pass - - @deprecated('3.1', alternative='np.iterable') def iterable(obj): """return true if *obj* is iterable""" @@ -380,12 +340,6 @@ def file_requires_unicode(x): return False -@deprecated('3.0', alternative='isinstance(..., numbers.Number)') -def is_numlike(obj): - """return true if *obj* looks like a number""" - return isinstance(obj, (numbers.Number, np.number)) - - def to_filehandle(fname, flag='r', return_opened=False, encoding=None): """ Convert a path to an open file handle or pass-through a file-like object. @@ -464,33 +418,22 @@ def get_sample_data(fname, asfileobj=True): `mpl-data/sample_data` directory. If *asfileobj* is `True` return a file object, otherwise just a file path. - Set the rc parameter examples.directory to the directory where we should - look, if sample_data files are stored in a location different than - default (which is 'mpl-data/sample_data` at the same level of 'matplotlib` - Python module files). + Sample data files are stored in the 'mpl-data/sample_data' directory within + the Matplotlib package. If the filename ends in .gz, the file is implicitly ungzipped. """ - # Don't trigger deprecation warning when just fetching. - if dict.__getitem__(matplotlib.rcParams, 'examples.directory'): - root = matplotlib.rcParams['examples.directory'] - else: - root = os.path.join(matplotlib._get_data_path(), 'sample_data') - path = os.path.join(root, fname) - + path = Path(matplotlib._get_data_path(), 'sample_data', fname) if asfileobj: - if os.path.splitext(fname)[-1].lower() in ['.csv', '.xrc', '.txt']: - mode = 'r' - else: - mode = 'rb' - - base, ext = os.path.splitext(fname) - if ext == '.gz': - return gzip.open(path, mode) + suffix = path.suffix.lower() + if suffix == '.gz': + return gzip.open(path) + elif suffix in ['.csv', '.xrc', '.txt']: + return path.open('r') else: - return open(path, mode) + return path.open('rb') else: - return path + return str(path) def flatten(seq, scalarp=is_scalar_or_string): @@ -515,38 +458,6 @@ def flatten(seq, scalarp=is_scalar_or_string): yield from flatten(item, scalarp) -@deprecated("3.0") -def mkdirs(newdir, mode=0o777): - """ - make directory *newdir* recursively, and set *mode*. Equivalent to :: - - > mkdir -p NEWDIR - > chmod MODE NEWDIR - """ - # this functionality is now in core python as of 3.2 - # LPY DROP - os.makedirs(newdir, mode=mode, exist_ok=True) - - -@deprecated('3.0') -class GetRealpathAndStat(object): - def __init__(self): - self._cache = {} - - def __call__(self, path): - result = self._cache.get(path) - if result is None: - realpath = os.path.realpath(path) - if sys.platform == 'win32': - stat_key = realpath - else: - stat = os.stat(realpath) - stat_key = (stat.st_ino, stat.st_dev) - result = realpath, stat_key - self._cache[path] = result - return result - - @functools.lru_cache() def get_realpath_and_stat(path): realpath = os.path.realpath(path) @@ -604,35 +515,6 @@ def dedent(s): return result -@deprecated("3.0") -def listFiles(root, patterns='*', recurse=1, return_folders=0): - """ - Recursively list files - - from Parmar and Martelli in the Python Cookbook - """ - import os.path - import fnmatch - # Expand patterns from semicolon-separated string to list - pattern_list = patterns.split(';') - results = [] - - for dirname, dirs, files in os.walk(root): - # Append to results all relevant files (and perhaps folders) - for name in files: - fullname = os.path.normpath(os.path.join(dirname, name)) - if return_folders or os.path.isfile(fullname): - for pattern in pattern_list: - if fnmatch.fnmatch(name, pattern): - results.append(fullname) - break - # Block recursion if recursion was disallowed - if not recurse: - break - - return results - - class maxdict(dict): """ A dictionary with a maximum size; this doesn't override all the @@ -1826,62 +1708,6 @@ def get_label(y, default_name): """ -@deprecated("3.0") -class Locked(object): - """ - Context manager to handle locks. - - Based on code from conda. - - (c) 2012-2013 Continuum Analytics, Inc. / https://www.continuum.io/ - All Rights Reserved - - conda is distributed under the terms of the BSD 3-clause license. - Consult LICENSE_CONDA or https://opensource.org/licenses/BSD-3-Clause. - """ - LOCKFN = '.matplotlib_lock' - - class TimeoutError(RuntimeError): - pass - - def __init__(self, path): - self.path = path - self.end = "-" + str(os.getpid()) - self.lock_path = os.path.join(self.path, self.LOCKFN + self.end) - self.pattern = os.path.join(self.path, self.LOCKFN + '-*') - self.remove = True - - def __enter__(self): - retries = 50 - sleeptime = 0.1 - while retries: - files = glob.glob(self.pattern) - if files and not files[0].endswith(self.end): - time.sleep(sleeptime) - retries -= 1 - else: - break - else: - err_str = _lockstr.format(self.pattern) - raise self.TimeoutError(err_str) - - if not files: - try: - os.makedirs(self.lock_path) - except OSError: - pass - else: # PID lock already here --- someone else will remove it. - self.remove = False - - def __exit__(self, exc_type, exc_value, traceback): - if self.remove: - for path in self.lock_path, self.path: - try: - os.rmdir(path) - except OSError: - pass - - @contextlib.contextmanager def _lock_path(path): """ diff --git a/lib/matplotlib/compat/subprocess.py b/lib/matplotlib/compat/subprocess.py deleted file mode 100644 index ad48ed4f137a..000000000000 --- a/lib/matplotlib/compat/subprocess.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -A replacement wrapper around the subprocess module, which provides a stub -implementation of subprocess members on Google App Engine -(which are missing in subprocess). - -Instead of importing subprocess, other modules should use this as follows: - -from matplotlib.compat import subprocess - -This module is safe to import from anywhere within matplotlib. -""" -import subprocess -from matplotlib.cbook import warn_deprecated -warn_deprecated(since='3.0', - name='matplotlib.compat.subprocess', - alternative='the python 3 standard library ' - '"subprocess" module', - obj_type='module') - -__all__ = ['Popen', 'PIPE', 'STDOUT', 'check_output', 'CalledProcessError'] - - -if hasattr(subprocess, 'Popen'): - Popen = subprocess.Popen - # Assume that it also has the other constants. - PIPE = subprocess.PIPE - STDOUT = subprocess.STDOUT - CalledProcessError = subprocess.CalledProcessError - check_output = subprocess.check_output -else: - # In restricted environments (such as Google App Engine), these are - # non-existent. Replace them with dummy versions that always raise OSError. - def Popen(*args, **kwargs): - raise OSError("subprocess.Popen is not supported") - - def check_output(*args, **kwargs): - raise OSError("subprocess.check_output is not supported") - PIPE = -1 - STDOUT = -2 - # There is no need to catch CalledProcessError. These stubs cannot raise - # it. None in an except clause will simply not match any exceptions. - CalledProcessError = None diff --git a/lib/matplotlib/container.py b/lib/matplotlib/container.py index bca712e39baf..3a3783d7332a 100644 --- a/lib/matplotlib/container.py +++ b/lib/matplotlib/container.py @@ -27,10 +27,6 @@ def __init__(self, kl, label=None): self.set_label(label) - @cbook.deprecated("3.0") - def set_remove_method(self, f): - self._remove_method = f - def remove(self): for c in cbook.flatten( self, scalarp=lambda x: isinstance(x, martist.Artist)): diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 264482600474..548620b429d9 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -199,13 +199,6 @@ def clabel(self, levels=None, *, self.labelTextsList = cbook.silent_list('text.Text', self.labelTexts) return self.labelTextsList - cl = cbook.deprecated("3.0", alternative="labelTexts")(property( - lambda self: self.labelTexts)) - cl_xy = cbook.deprecated("3.0", alternative="labelXYs")(property( - lambda self: self.labelXYs)) - cl_cvalues = cbook.deprecated("3.0", alternative="labelCValues")(property( - lambda self: self.labelCValues)) - def print_label(self, linecontour, labelwidth): "Return *False* if contours are too short for a label." return (len(linecontour) > 10 * labelwidth diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index 3f152d10abaf..0fbc63ec3f0d 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -610,113 +610,6 @@ def __call__(self, x, pos=0): def set_tzinfo(self, tz): self.tz = tz - @cbook.deprecated("3.0") - def _replace_common_substr(self, s1, s2, sub1, sub2, replacement): - """Helper function for replacing substrings sub1 and sub2 - located at the same indexes in strings s1 and s2 respectively, - with the string replacement. It is expected that sub1 and sub2 - have the same length. Returns the pair s1, s2 after the - substitutions. - """ - # Find common indexes of substrings sub1 in s1 and sub2 in s2 - # and make substitutions inplace. Because this is inplace, - # it is okay if len(replacement) != len(sub1), len(sub2). - i = 0 - while True: - j = s1.find(sub1, i) - if j == -1: - break - - i = j + 1 - if s2[j:j + len(sub2)] != sub2: - continue - - s1 = s1[:j] + replacement + s1[j + len(sub1):] - s2 = s2[:j] + replacement + s2[j + len(sub2):] - - return s1, s2 - - @cbook.deprecated("3.0") - def strftime_pre_1900(self, dt, fmt=None): - """Call time.strftime for years before 1900 by rolling - forward a multiple of 28 years. - - *fmt* is a :func:`strftime` format string. - - Dalke: I hope I did this math right. Every 28 years the - calendar repeats, except through century leap years excepting - the 400 year leap years. But only if you're using the Gregorian - calendar. - """ - if fmt is None: - fmt = self.fmt - - # Since python's time module's strftime implementation does not - # support %f microsecond (but the datetime module does), use a - # regular expression substitution to replace instances of %f. - # Note that this can be useful since python's floating-point - # precision representation for datetime causes precision to be - # more accurate closer to year 0 (around the year 2000, precision - # can be at 10s of microseconds). - fmt = re.sub(r'((^|[^%])(%%)*)%f', - r'\g<1>{0:06d}'.format(dt.microsecond), fmt) - - year = dt.year - # For every non-leap year century, advance by - # 6 years to get into the 28-year repeat cycle - delta = 2000 - year - off = 6 * (delta // 100 + delta // 400) - year = year + off - - # Move to between the years 1973 and 2000 - year1 = year + ((2000 - year) // 28) * 28 - year2 = year1 + 28 - timetuple = dt.timetuple() - # Generate timestamp string for year and year+28 - s1 = time.strftime(fmt, (year1,) + timetuple[1:]) - s2 = time.strftime(fmt, (year2,) + timetuple[1:]) - - # Replace instances of respective years (both 2-digit and 4-digit) - # that are located at the same indexes of s1, s2 with dt's year. - # Note that C++'s strftime implementation does not use padded - # zeros or padded whitespace for %y or %Y for years before 100, but - # uses padded zeros for %x. (For example, try the runnable examples - # with .tm_year in the interval [-1900, -1800] on - # http://en.cppreference.com/w/c/chrono/strftime.) For ease of - # implementation, we always use padded zeros for %y, %Y, and %x. - s1, s2 = self._replace_common_substr(s1, s2, - "{0:04d}".format(year1), - "{0:04d}".format(year2), - "{0:04d}".format(dt.year)) - s1, s2 = self._replace_common_substr(s1, s2, - "{0:02d}".format(year1 % 100), - "{0:02d}".format(year2 % 100), - "{0:02d}".format(dt.year % 100)) - return cbook.unicode_safe(s1) - - @cbook.deprecated("3.0") - def strftime(self, dt, fmt=None): - """ - Refer to documentation for :meth:`datetime.datetime.strftime` - - *fmt* is a :meth:`datetime.datetime.strftime` format string. - - Warning: For years before 1900, depending upon the current - locale it is possible that the year displayed with %x might - be incorrect. For years before 100, %y and %Y will yield - zero-padded strings. - """ - if fmt is None: - fmt = self.fmt - fmt = self.illegal_s.sub(r"\1", fmt) - fmt = fmt.replace("%s", "s") - if dt.year >= 1900: - # Note: in python 3.3 this is okay for years >= 1000, - # refer to http://bugs.python.org/issue1777412 - return cbook.unicode_safe(dt.strftime(fmt)) - - return self.strftime_pre_1900(dt, fmt) - class IndexDateFormatter(ticker.Formatter): """ diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index d3ef6f433b3f..c6b8ebed7929 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -926,44 +926,6 @@ def _normalize_font_family(family): return family -@cbook.deprecated("3.0") -class TempCache(object): - """ - A class to store temporary caches that are (a) not saved to disk - and (b) invalidated whenever certain font-related - rcParams---namely the family lookup lists---are changed or the - font cache is reloaded. This avoids the expensive linear search - through all fonts every time a font is looked up. - """ - # A list of rcparam names that, when changed, invalidated this - # cache. - invalidating_rcparams = ( - 'font.serif', 'font.sans-serif', 'font.cursive', 'font.fantasy', - 'font.monospace') - - def __init__(self): - self._lookup_cache = {} - self._last_rcParams = self.make_rcparams_key() - - def make_rcparams_key(self): - return [id(fontManager)] + [ - rcParams[param] for param in self.invalidating_rcparams] - - def get(self, prop): - key = self.make_rcparams_key() - if key != self._last_rcParams: - self._lookup_cache = {} - self._last_rcParams = key - return self._lookup_cache.get(prop) - - def set(self, prop, value): - key = self.make_rcparams_key() - if key != self._last_rcParams: - self._lookup_cache = {} - self._last_rcParams = key - self._lookup_cache[prop] = value - - class FontManager(object): """ On import, the :class:`FontManager` singleton instance creates a @@ -1012,16 +974,6 @@ def __init__(self, size=None, weight='normal'): + findSystemFonts(fontext='afm')) self.afmlist = createFontList(afmfiles, fontext='afm') - @cbook.deprecated("3.0") - @property - def ttffiles(self): - return [font.fname for font in self.ttflist] - - @cbook.deprecated("3.0") - @property - def afmfiles(self): - return [font.fname for font in self.afmlist] - @property def defaultFont(self): # Lazily evaluated (findfont then caches the result) to avoid including diff --git a/lib/matplotlib/markers.py b/lib/matplotlib/markers.py index cf63085473af..46c4f8fe9e65 100644 --- a/lib/matplotlib/markers.py +++ b/lib/matplotlib/markers.py @@ -298,7 +298,7 @@ def set_marker(self, marker): elif isinstance(marker, Path): self._marker_function = self._set_path_marker elif (isinstance(marker, Sized) and len(marker) in (2, 3) and - marker[1] in (0, 1, 2, 3)): + marker[1] in (0, 1, 2)): self._marker_function = self._set_tuple_marker elif (not isinstance(marker, (np.ndarray, list)) and marker in self.markers): @@ -350,37 +350,23 @@ def _set_vertices(self): def _set_tuple_marker(self): marker = self._marker - if isinstance(marker[0], Number): - if len(marker) == 2: - numsides, rotation = marker[0], 0.0 - elif len(marker) == 3: - numsides, rotation = marker[0], marker[2] - symstyle = marker[1] - if symstyle == 0: - self._path = Path.unit_regular_polygon(numsides) - self._joinstyle = 'miter' - elif symstyle == 1: - self._path = Path.unit_regular_star(numsides) - self._joinstyle = 'bevel' - elif symstyle == 2: - self._path = Path.unit_regular_asterisk(numsides) - self._filled = False - self._joinstyle = 'bevel' - elif symstyle == 3: - cbook.warn_deprecated( - "3.0", message="Setting a circle marker using `(..., 3)` " - "is deprecated since Matplotlib 3.0, and support for it " - "will be removed in 3.2. Directly pass 'o' instead.") - self._path = Path.unit_circle() - self._transform = Affine2D().scale(0.5).rotate_deg(rotation) + if len(marker) == 2: + numsides, rotation = marker[0], 0.0 + elif len(marker) == 3: + numsides, rotation = marker[0], marker[2] + symstyle = marker[1] + if symstyle == 0: + self._path = Path.unit_regular_polygon(numsides) + self._joinstyle = 'miter' + elif symstyle == 1: + self._path = Path.unit_regular_star(numsides) + self._joinstyle = 'bevel' + elif symstyle == 2: + self._path = Path.unit_regular_asterisk(numsides) + self._filled = False + self._joinstyle = 'bevel' else: - cbook.warn_deprecated( - "3.0", message="Passing vertices as `(verts, 0)` is " - "deprecated since Matplotlib 3.0, and support for it will be " - "removed in 3.2. Directly pass `verts` instead.") - verts = np.asarray(marker[0]) - path = Path(verts) - self._set_custom_marker(path) + raise ValueError(f"Unexpected tuple marker: {marker}") def _set_mathtext_path(self): """ diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index 3e6026e25fdc..9018e7d6bed3 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -81,9 +81,6 @@ def get_unicode_index(symbol, math=True): .format(symbol)) -unichr_safe = cbook.deprecated("3.0")(chr) - - class MathtextBackend(object): """ The base class for the mathtext backend-specific code. The diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 9c8966825730..ee94d5d82c4b 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -583,9 +583,9 @@ def _convert_xy_units(self, xy): patchdoc = artist.kwdoc(Patch) -for k in ('Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow', - 'FancyArrow', 'YAArrow', 'CirclePolygon', 'Ellipse', 'Arc', - 'FancyBboxPatch', 'Patch'): +for k in ['Rectangle', 'Circle', 'RegularPolygon', 'Polygon', 'Wedge', 'Arrow', + 'FancyArrow', 'CirclePolygon', 'Ellipse', 'Arc', 'FancyBboxPatch', + 'Patch']: docstring.interpd.update({k: patchdoc}) # define Patch.__init__ docstring after the class has been added to interpd @@ -1294,108 +1294,6 @@ def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, docstring.interpd.update({"FancyArrow": FancyArrow.__init__.__doc__}) -@cbook.deprecated("3.0", alternative="FancyArrowPatch") -class YAArrow(Patch): - """ - Yet another arrow class. - - This is an arrow that is defined in display space and has a tip at - *x1*, *y1* and a base at *x2*, *y2*. - """ - def __str__(self): - return "YAArrow()" - - @docstring.dedent_interpd - def __init__(self, figure, xytip, xybase, - width=4, frac=0.1, headwidth=12, **kwargs): - """ - Constructor arguments: - - *xytip* - (*x*, *y*) location of arrow tip - - *xybase* - (*x*, *y*) location the arrow base mid point - - *figure* - The `Figure` instance (used to get the dpi setting). - - *width* - The width of the arrow in points - - *frac* - The fraction of the arrow length occupied by the head - - *headwidth* - The width of the base of the arrow head in points - - Valid kwargs are: - %(Patch)s - - """ - self.xytip = xytip - self.xybase = xybase - self.width = width - self.frac = frac - self.headwidth = headwidth - Patch.__init__(self, **kwargs) - # Set self.figure after Patch.__init__, since it sets self.figure to - # None - self.figure = figure - - def get_path(self): - # Since this is dpi dependent, we need to recompute the path - # every time. - - # the base vertices - x1, y1 = self.xytip - x2, y2 = self.xybase - k1 = self.width * self.figure.dpi / 72. / 2. - k2 = self.headwidth * self.figure.dpi / 72. / 2. - xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1) - - # a point on the segment 20% of the distance from the tip to the base - xm = x1 + self.frac * (x2 - x1) - ym = y1 + self.frac * (y2 - y1) - xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1) - xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2) - - xs = self.convert_xunits([xb1, xb2, xc2, xd2, x1, xd1, xc1, xb1]) - ys = self.convert_yunits([yb1, yb2, yc2, yd2, y1, yd1, yc1, yb1]) - - return Path(np.column_stack([xs, ys]), closed=True) - - def get_patch_transform(self): - return transforms.IdentityTransform() - - def getpoints(self, x1, y1, x2, y2, k): - """ - For line segment defined by (*x1*, *y1*) and (*x2*, *y2*) - return the points on the line that is perpendicular to the - line and intersects (*x2*, *y2*) and the distance from (*x2*, - *y2*) of the returned points is *k*. - """ - x1, y1, x2, y2, k = map(float, (x1, y1, x2, y2, k)) - - if y2 - y1 == 0: - return x2, y2 + k, x2, y2 - k - elif x2 - x1 == 0: - return x2 + k, y2, x2 - k, y2 - - m = (y2 - y1) / (x2 - x1) - pm = -1. / m - a = 1 - b = -2 * y2 - c = y2 ** 2. - k ** 2. * pm ** 2. / (1. + pm ** 2.) - - y3a = (-b + math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) - x3a = (y3a - y2) / pm + x2 - - y3b = (-b - math.sqrt(b ** 2 - 4 * a * c)) / (2 * a) - x3b = (y3b - y2) / pm + x2 - return x3a, y3a, x3b, y3b - - class CirclePolygon(RegularPolygon): """ A polygon-approximation of a circle patch. diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 4f266917e47f..cbd2b9ee5324 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -67,7 +67,7 @@ Locator, IndexLocator, FixedLocator, NullLocator,\ LinearLocator, LogLocator, AutoLocator, MultipleLocator,\ MaxNLocator -from matplotlib.backends import pylab_setup, _get_running_interactive_framework +from matplotlib.backends import _get_running_interactive_framework _log = logging.getLogger(__name__) @@ -2629,14 +2629,13 @@ def hist( x, bins=None, range=None, density=None, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, - label=None, stacked=False, normed=None, *, data=None, - **kwargs): + label=None, stacked=False, *, data=None, **kwargs): return gca().hist( x, bins=bins, range=range, density=density, weights=weights, cumulative=cumulative, bottom=bottom, histtype=histtype, align=align, orientation=orientation, rwidth=rwidth, log=log, - color=color, label=label, stacked=stacked, normed=normed, - **({"data": data} if data is not None else {}), **kwargs) + color=color, label=label, stacked=stacked, **({"data": data} + if data is not None else {}), **kwargs) # Autogenerated by boilerplate.py. Do not edit as changes will be lost. @@ -2834,7 +2833,8 @@ def quiverkey(Q, X, Y, U, label, **kw): @docstring.copy(Axes.scatter) def scatter( x, y, s=None, c=None, marker=None, cmap=None, norm=None, - vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, + vmin=None, vmax=None, alpha=None, linewidths=None, + verts=cbook.deprecation._deprecated_parameter, edgecolors=None, *, plotnonfinite=False, data=None, **kwargs): __ret = gca().scatter( x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm, diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index ffc18f0eaada..7b1cba8fa8ce 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -1458,9 +1458,6 @@ def _validate_linestyle(ls): 'keymap.help': [['f1'], validate_stringlist], 'keymap.copy': [['ctrl+c', 'cmd+c'], validate_stringlist], - # sample data - 'examples.directory': ['', validate_string], - # Animation settings 'animation.html': ['none', validate_movie_html_fmt], # Limit, in MB, of size of base64 encoded animation in HTML diff --git a/lib/matplotlib/sphinxext/plot_directive.py b/lib/matplotlib/sphinxext/plot_directive.py index a66d935f88e5..9acdf8b00753 100644 --- a/lib/matplotlib/sphinxext/plot_directive.py +++ b/lib/matplotlib/sphinxext/plot_directive.py @@ -352,13 +352,6 @@ def split_code_at_show(text): return parts -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(r"^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE) - return sub_re.sub("", text) - - # ----------------------------------------------------------------------------- # Template # ----------------------------------------------------------------------------- diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index 8b4b9af3dae9..05a75576334d 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -455,7 +455,6 @@ def contains(self, mouseevent): def get_children(self): """Return the Artists contained by the table.""" return list(self._cells.values()) - get_child_artists = cbook.deprecated("3.0")(get_children) def get_window_extent(self, renderer): """Return the bounding box of the table in window coords.""" diff --git a/lib/matplotlib/testing/__init__.py b/lib/matplotlib/testing/__init__.py index 5c01e95c488d..95bdbe87a500 100644 --- a/lib/matplotlib/testing/__init__.py +++ b/lib/matplotlib/testing/__init__.py @@ -18,14 +18,6 @@ def is_called_from_pytest(): return getattr(mpl, '_called_from_pytest', False) -def _wants_nose(): - wants_nose = (not getattr(mpl, '_called_from_pytest', False) - and 'nose' in sys.modules) - if wants_nose: - cbook.warn_deprecated("3.2", name="support for nose-based tests") - return wants_nose - - def set_font_settings_for_testing(): mpl.rcParams['font.family'] = 'DejaVu Sans' mpl.rcParams['text.hinting'] = False diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py index e7072874b40a..e5b348114c50 100644 --- a/lib/matplotlib/testing/compare.py +++ b/lib/matplotlib/testing/compare.py @@ -19,7 +19,7 @@ from matplotlib.testing.exceptions import ImageComparisonFailure from matplotlib import cbook -__all__ = ['compare_float', 'compare_images', 'comparable_formats'] +__all__ = ['compare_images', 'comparable_formats'] def make_test_filename(fname, purpose): @@ -31,50 +31,6 @@ def make_test_filename(fname, purpose): return '%s-%s%s' % (base, purpose, ext) -@cbook.deprecated("3.0") -def compare_float(expected, actual, relTol=None, absTol=None): - """ - Fail if the floating point values are not close enough, with - the given message. - - You can specify a relative tolerance, absolute tolerance, or both. - - """ - if relTol is None and absTol is None: - raise ValueError("You haven't specified a 'relTol' relative " - "tolerance or a 'absTol' absolute tolerance " - "function argument. You must specify one.") - msg = "" - - if absTol is not None: - absDiff = abs(expected - actual) - if absTol < absDiff: - template = ['', - 'Expected: {expected}', - 'Actual: {actual}', - 'Abs diff: {absDiff}', - 'Abs tol: {absTol}'] - msg += '\n '.join([line.format(**locals()) for line in template]) - - if relTol is not None: - # The relative difference of the two values. If the expected value is - # zero, then return the absolute value of the difference. - relDiff = abs(expected - actual) - if expected: - relDiff = relDiff / abs(expected) - - if relTol < relDiff: - # The relative difference is a ratio, so it's always unit-less. - template = ['', - 'Expected: {expected}', - 'Actual: {actual}', - 'Rel diff: {relDiff}', - 'Rel tol: {relTol}'] - msg += '\n '.join([line.format(**locals()) for line in template]) - - return msg or None - - def get_cache_dir(): cachedir = mpl.get_cachedir() if cachedir is None: @@ -310,13 +266,8 @@ def convert(filename, cache): """ base, extension = filename.rsplit('.', 1) if extension not in converter: - reason = "Don't know how to convert %s files to png" % extension - if mpl.testing._wants_nose(): - from nose import SkipTest - raise SkipTest(reason) - else: - import pytest - pytest.skip(reason) + import pytest + pytest.skip(f"Don't know how to convert {extension} files to png") newname = base + '_' + extension + '.png' if not os.path.exists(filename): raise IOError("'%s' does not exist" % filename) diff --git a/lib/matplotlib/testing/decorators.py b/lib/matplotlib/testing/decorators.py index 186a806f59fc..2d955baff0e9 100644 --- a/lib/matplotlib/testing/decorators.py +++ b/lib/matplotlib/testing/decorators.py @@ -45,15 +45,6 @@ def tearDownClass(cls): cls._cm.__exit__(None, None, None) -@cbook.deprecated("3.0") -class CleanupTest(object): - setup_class = classmethod(CleanupTestCase.setUpClass.__func__) - teardown_class = classmethod(CleanupTestCase.tearDownClass.__func__) - - def test(self): - self._func() - - def cleanup(style=None): """ A decorator to ensure that any global state is reset before @@ -231,65 +222,6 @@ def compare(self, idx, baseline, extension): _raise_on_image_difference(expected_fname, actual_fname, self.tol) -@cbook.deprecated("3.0") -class ImageComparisonTest(CleanupTest, _ImageComparisonBase): - """ - Nose-based image comparison class - - This class generates tests for a nose-based testing framework. Ideally, - this class would not be public, and the only publicly visible API would - be the :func:`image_comparison` decorator. Unfortunately, there are - existing downstream users of this class (e.g., pytest-mpl) so it cannot yet - be removed. - """ - def __init__(self, baseline_images, extensions, tol, - freetype_version, remove_text, savefig_kwargs, style): - _ImageComparisonBase.__init__(self, tol, remove_text, savefig_kwargs) - self.baseline_images = baseline_images - self.extensions = extensions - self.freetype_version = freetype_version - self.style = style - - def setup(self): - func = self.func - plt.close('all') - self.setup_class() - try: - matplotlib.style.use(self.style) - matplotlib.testing.set_font_settings_for_testing() - func() - assert len(plt.get_fignums()) == len(self.baseline_images), ( - "Test generated {} images but there are {} baseline images" - .format(len(plt.get_fignums()), len(self.baseline_images))) - except: - # Restore original settings before raising errors. - self.teardown_class() - raise - - def teardown(self): - self.teardown_class() - - def nose_runner(self): - func = self.compare - func = _checked_on_freetype_version(self.freetype_version)(func) - funcs = {extension: _skip_if_format_is_uncomparable(extension)(func) - for extension in self.extensions} - for idx, baseline in enumerate(self.baseline_images): - for extension in self.extensions: - yield funcs[extension], idx, baseline, extension - - def __call__(self, func): - self.delayed_init(func) - import nose.tools - - @functools.wraps(func) - @nose.tools.with_setup(self.setup, self.teardown) - def runner_wrapper(): - yield from self.nose_runner() - - return runner_wrapper - - def _pytest_image_comparison(baseline_images, extensions, tol, freetype_version, remove_text, savefig_kwargs, style): @@ -418,24 +350,12 @@ def image_comparison(baseline_images, extensions=None, tol=0, if extensions is None: # Default extensions to test, if not set via baseline_images. extensions = ['png', 'pdf', 'svg'] - if savefig_kwarg is None: - #default no kwargs to savefig - savefig_kwarg = dict() - - if mpl.testing._wants_nose(): - if baseline_images is None: - raise ValueError('baseline_images must be specified') - - return ImageComparisonTest( - baseline_images=baseline_images, extensions=extensions, tol=tol, - freetype_version=freetype_version, remove_text=remove_text, - savefig_kwargs=savefig_kwarg, style=style) - else: - return _pytest_image_comparison( - baseline_images=baseline_images, extensions=extensions, tol=tol, - freetype_version=freetype_version, remove_text=remove_text, - savefig_kwargs=savefig_kwarg, style=style) + savefig_kwarg = dict() # default no kwargs to savefig + return _pytest_image_comparison( + baseline_images=baseline_images, extensions=extensions, tol=tol, + freetype_version=freetype_version, remove_text=remove_text, + savefig_kwargs=savefig_kwarg, style=style) def check_figures_equal(*, extensions=("png", "pdf", "svg"), tol=0): @@ -543,25 +463,3 @@ def backend_switcher(*args, **kwargs): return backend_switcher return switch_backend_decorator - - -@cbook.deprecated("3.0") -def skip_if_command_unavailable(cmd): - """ - skips a test if a command is unavailable. - - Parameters - ---------- - cmd : list of str - must be a complete command which should not - return a non zero exit code, something like - ["latex", "-version"] - """ - from subprocess import check_output - try: - check_output(cmd) - except Exception: - import pytest - return pytest.mark.skip(reason='missing command: %s' % cmd[0]) - - return lambda f: f diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index f991e21b74d8..dd259d6ba132 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -3170,32 +3170,14 @@ def test_hist_stacked_step(): ax.hist((d1, d2), histtype="step", stacked=True) -@image_comparison(['hist_stacked_normed', 'hist_stacked_normed']) +@image_comparison(['hist_stacked_normed']) def test_hist_stacked_density(): # make some data d1 = np.linspace(1, 3, 20) d2 = np.linspace(0, 10, 50) - fig, ax = plt.subplots() ax.hist((d1, d2), stacked=True, density=True) - # Also check that the old keyword works. - fig, ax = plt.subplots() - with pytest.warns(UserWarning): - ax.hist((d1, d2), stacked=True, normed=True) - - -@pytest.mark.parametrize('normed', [False, True]) -@pytest.mark.parametrize('density', [False, True]) -def test_hist_normed_density(normed, density): - # Normed and density should not be used simultaneously - d1 = np.linspace(1, 3, 20) - d2 = np.linspace(0, 10, 50) - fig, ax = plt.subplots() - # test that kwargs normed and density cannot be set both. - with pytest.raises(Exception): - ax.hist((d1, d2), stacked=True, normed=normed, density=density) - @image_comparison(['hist_step_bottom.png'], remove_text=True) def test_hist_step_bottom(): diff --git a/lib/matplotlib/tests/test_dates.py b/lib/matplotlib/tests/test_dates.py index 31a5498e4597..a3fd97d5f2de 100644 --- a/lib/matplotlib/tests/test_dates.py +++ b/lib/matplotlib/tests/test_dates.py @@ -252,55 +252,6 @@ def test_locator_set_formatter(): assert ticklabels == expected -def test_date_formatter_strftime(): - """ - Tests that DateFormatter matches datetime.strftime, - check microseconds for years before 1900 for bug #3179 - as well as a few related issues for years before 1900. - """ - def test_strftime_fields(dt): - """For datetime object dt, check DateFormatter fields""" - # Note: the last couple of %%s are to check multiple %s are handled - # properly; %% should get replaced by %. - formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x") - # Compute date fields without using datetime.strftime, - # since datetime.strftime does not work before year 1900 - formatted_date_str = ( - "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} " - "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} " - "%{microsecond:06d} %x" - .format( - weekday=str((dt.weekday() + 1) % 7), - day=dt.day, - month=dt.month, - year=dt.year % 100, - full_year=dt.year, - hour24=dt.hour, - hour12=((dt.hour-1) % 12) + 1, - minute=dt.minute, - second=dt.second, - microsecond=dt.microsecond)) - with pytest.warns(MatplotlibDeprecationWarning): - assert formatter.strftime(dt) == formatted_date_str - - try: - # Test strftime("%x") with the current locale. - import locale # Might not exist on some platforms, such as Windows - locale_formatter = mdates.DateFormatter("%x") - locale_d_fmt = locale.nl_langinfo(locale.D_FMT) - expanded_formatter = mdates.DateFormatter(locale_d_fmt) - with pytest.warns(MatplotlibDeprecationWarning): - assert locale_formatter.strftime(dt) == \ - expanded_formatter.strftime(dt) - except (ImportError, AttributeError): - pass - - for year in range(1, 3000, 71): - # Iterate through random set of years - test_strftime_fields(datetime.datetime(year, 1, 1)) - test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) - - def test_date_formatter_callable(): scale = -11 locator = Mock(_get_unit=Mock(return_value=scale)) diff --git a/lib/matplotlib/tests/test_mlab.py b/lib/matplotlib/tests/test_mlab.py index 4d964c2a2837..39a898062c51 100644 --- a/lib/matplotlib/tests/test_mlab.py +++ b/lib/matplotlib/tests/test_mlab.py @@ -10,14 +10,6 @@ from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning -''' -A lot of mlab.py has been deprecated in Matplotlib 2.2 and is scheduled for -removal in the future. The tests that use deprecated methods have a block -to catch the deprecation warning, and can be removed with the mlab code is -removed. -''' - - def _stride_repeat(*args, **kwargs): with pytest.warns(MatplotlibDeprecationWarning): return mlab.stride_repeat(*args, **kwargs) diff --git a/lib/matplotlib/tests/test_patches.py b/lib/matplotlib/tests/test_patches.py index 1a801168a37e..e047ea696e97 100644 --- a/lib/matplotlib/tests/test_patches.py +++ b/lib/matplotlib/tests/test_patches.py @@ -341,10 +341,6 @@ def test_patch_str(): s = mpatches.Shadow(p, 1, 1) assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))" - with pytest.warns(MatplotlibDeprecationWarning): - p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1) - assert str(p) == "YAArrow()" - # Not testing Arrow, FancyArrow here # because they seem to exist only for historical reasons. diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index cadde6ea856a..62f78a808404 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -442,9 +442,6 @@ def test_if_rctemplate_is_up_to_date(): continue if k in deprecated: continue - if k.startswith( - ("verbose.", "examples.directory", "text.latex.unicode")): - continue found = False for line in rclines: if k in line: diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index 8450b60d0891..6b0b8ba95172 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -2406,11 +2406,5 @@ def get_window_extent(self, renderer=None): return Bbox.union(bboxes) - arrow = property( - fget=cbook.deprecated("3.0", message="arrow was deprecated in " - "Matplotlib 3.0 and will be removed in 3.2. Use arrow_patch " - "instead.")(lambda self: None), - fset=cbook.deprecated("3.0")(lambda self, value: None)) - docstring.interpd.update(Annotation=Annotation.__init__.__doc__) diff --git a/lib/matplotlib/textpath.py b/lib/matplotlib/textpath.py index d170343425be..c340c8147b3d 100644 --- a/lib/matplotlib/textpath.py +++ b/lib/matplotlib/textpath.py @@ -26,11 +26,6 @@ def __init__(self): self.mathtext_parser = MathTextParser('path') self._texmanager = None - @property - @cbook.deprecated("3.0") - def tex_font_map(self): - return dviread.PsfontsMap(dviread.find_tex_file('pdftex.map')) - def _get_font(self, prop): """ Find the `FT2Font` matching font properties *prop*, with its size set. diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 4c89181fa2b2..596e6ce436d5 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -1736,53 +1736,6 @@ def view_limits(self, vmin, vmax): return mtransforms.nonsingular(vmin, vmax) -@cbook.deprecated("3.0") -def closeto(x, y): - return abs(x - y) < 1e-10 - - -@cbook.deprecated("3.0") -class Base(object): - 'this solution has some hacks to deal with floating point inaccuracies' - def __init__(self, base): - if base <= 0: - raise ValueError("'base' must be positive") - self._base = base - - def lt(self, x): - 'return the largest multiple of base < x' - d, m = divmod(x, self._base) - if closeto(m, 0) and not closeto(m / self._base, 1): - return (d - 1) * self._base - return d * self._base - - def le(self, x): - 'return the largest multiple of base <= x' - d, m = divmod(x, self._base) - if closeto(m / self._base, 1): # was closeto(m, self._base) - #looks like floating point error - return (d + 1) * self._base - return d * self._base - - def gt(self, x): - 'return the smallest multiple of base > x' - d, m = divmod(x, self._base) - if closeto(m / self._base, 1): - #looks like floating point error - return (d + 2) * self._base - return (d + 1) * self._base - - def ge(self, x): - 'return the smallest multiple of base >= x' - d, m = divmod(x, self._base) - if closeto(m, 0) and not closeto(m / self._base, 1): - return d * self._base - return (d + 1) * self._base - - def get_base(self): - return self._base - - class MultipleLocator(Locator): """ Set a tick on each integer multiple of a base within the view interval. @@ -2129,14 +2082,6 @@ def decade_up(x, base=10): return base ** lx -def nearest_long(x): - 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): if not np.isfinite(x): return False diff --git a/lib/mpl_toolkits/axes_grid/__init__.py b/lib/mpl_toolkits/axes_grid/__init__.py index f711daec253f..2d227d50010c 100644 --- a/lib/mpl_toolkits/axes_grid/__init__.py +++ b/lib/mpl_toolkits/axes_grid/__init__.py @@ -1,6 +1,5 @@ from . import axes_size as Size -from .axes_divider import Divider, SubplotDivider, LocatableAxes, \ - make_axes_locatable +from .axes_divider import Divider, SubplotDivider, make_axes_locatable from .axes_grid import Grid, ImageGrid, AxesGrid #from axes_divider import make_axes_locatable from matplotlib.cbook import warn_deprecated diff --git a/lib/mpl_toolkits/axes_grid/axes_divider.py b/lib/mpl_toolkits/axes_grid/axes_divider.py index 87760bbb0dc4..33b4e512c9a0 100644 --- a/lib/mpl_toolkits/axes_grid/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid/axes_divider.py @@ -1,5 +1,3 @@ from mpl_toolkits.axes_grid1.axes_divider import ( - AxesDivider, AxesLocator, Divider, SubplotDivider, locatable_axes_factory, - make_axes_locatable) -from mpl_toolkits.axisartist.axes_divider import LocatableAxes + AxesDivider, AxesLocator, Divider, SubplotDivider, make_axes_locatable) from mpl_toolkits.axisartist.axislines import Axes diff --git a/lib/mpl_toolkits/axes_grid/axes_grid.py b/lib/mpl_toolkits/axes_grid/axes_grid.py index db7507bb8254..893b7800ccde 100644 --- a/lib/mpl_toolkits/axes_grid/axes_grid.py +++ b/lib/mpl_toolkits/axes_grid/axes_grid.py @@ -1,3 +1,2 @@ -from mpl_toolkits.axisartist.axes_divider import LocatableAxes from mpl_toolkits.axisartist.axes_grid import ( AxesGrid, CbarAxes, Grid, ImageGrid) diff --git a/lib/mpl_toolkits/axes_grid1/__init__.py b/lib/mpl_toolkits/axes_grid1/__init__.py index 2109556cfe70..0f359c9e01f3 100644 --- a/lib/mpl_toolkits/axes_grid1/__init__.py +++ b/lib/mpl_toolkits/axes_grid1/__init__.py @@ -1,7 +1,5 @@ from . import axes_size as Size -from .axes_divider import Divider, SubplotDivider, LocatableAxes, \ - make_axes_locatable +from .axes_divider import Divider, SubplotDivider, make_axes_locatable from .axes_grid import Grid, ImageGrid, AxesGrid -#from axes_divider import make_axes_locatable from .parasite_axes import host_subplot, host_axes diff --git a/lib/mpl_toolkits/axes_grid1/axes_divider.py b/lib/mpl_toolkits/axes_grid1/axes_divider.py index 971897c95f53..e51f6c9a0c7a 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid1/axes_divider.py @@ -854,22 +854,6 @@ def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None): return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) -@cbook.deprecated('3.0', - addendum=' There is no alternative. Deriving from ' - 'matplotlib.axes.Axes provides this functionality ' - 'already.') -class LocatableAxesBase(object): - pass - - -@cbook.deprecated('3.0', - addendum=' There is no alternative. Classes derived from ' - 'matplotlib.axes.Axes provide this functionality ' - 'already.') -def locatable_axes_factory(axes_class): - return axes_class - - def make_axes_locatable(axes): divider = AxesDivider(axes) locator = divider.new_locator(nx=0, ny=0) @@ -890,18 +874,3 @@ def make_axes_area_auto_adjustable(ax, divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad, adjust_dirs=adjust_dirs) - - -from .mpl_axes import Axes as _Axes - - -@cbook.deprecated('3.0', - alternative='mpl_toolkits.axes_grid1.mpl_axes.Axes') -class Axes(_Axes): - pass - - -@cbook.deprecated('3.0', - alternative='mpl_toolkits.axes_grid1.mpl_axes.Axes') -class LocatableAxes(_Axes): - pass diff --git a/lib/mpl_toolkits/axisartist/axes_divider.py b/lib/mpl_toolkits/axisartist/axes_divider.py index 9287adb8b7f7..3b177838f896 100644 --- a/lib/mpl_toolkits/axisartist/axes_divider.py +++ b/lib/mpl_toolkits/axisartist/axes_divider.py @@ -1,19 +1,2 @@ -from matplotlib import cbook - from mpl_toolkits.axes_grid1.axes_divider import ( - Divider, AxesLocator, SubplotDivider, AxesDivider, locatable_axes_factory, - make_axes_locatable) - -from mpl_toolkits.axisartist.axislines import Axes as _Axes - - -@cbook.deprecated('3.0', - alternative='mpl_toolkits.axisartist.axislines.Axes') -class Axes(_Axes): - pass - - -@cbook.deprecated('3.0', - alternative='mpl_toolkits.axisartist.axislines.Axes') -class LocatableAxes(_Axes): - pass + Divider, AxesLocator, SubplotDivider, AxesDivider, make_axes_locatable) diff --git a/src/_tkagg.cpp b/src/_tkagg.cpp index 51e6c4d6d976..760b4b0efd84 100644 --- a/src/_tkagg.cpp +++ b/src/_tkagg.cpp @@ -46,171 +46,6 @@ static Tk_FindPhoto_t TK_FIND_PHOTO; static Tk_PhotoPutBlock_NoComposite_t TK_PHOTO_PUT_BLOCK_NO_COMPOSITE; static Tk_PhotoBlank_t TK_PHOTO_BLANK; -static int PyAggImagePhoto(ClientData clientdata, Tcl_Interp *interp, int - argc, char **argv) -{ - Tk_PhotoHandle photo; - Tk_PhotoImageBlock block; - - // vars for blitting - - size_t pdata; - int wdata, hdata, bbox_parse; - float x1, x2, y1, y2; - bool has_bbox; - agg::int8u *destbuffer, *buffer; - int destx, desty, destwidth, destheight, deststride; - - long mode; - long nval; - if (TK_MAIN_WINDOW(interp) == NULL) { - // Will throw a _tkinter.TclError with "this isn't a Tk application" - return TCL_ERROR; - } - - if (argc != 5) { - TCL_APPEND_RESULT(interp, "usage: ", argv[0], " destPhoto srcImage", (char *)NULL); - return TCL_ERROR; - } - - /* get Tcl PhotoImage handle */ - photo = TK_FIND_PHOTO(interp, argv[1]); - if (photo == NULL) { - TCL_APPEND_RESULT(interp, "destination photo must exist", (char *)NULL); - return TCL_ERROR; - } - /* get buffer from str which is "height width ptr" */ - if (sscanf(argv[2], IMG_FORMAT, &hdata, &wdata, &pdata) != 3) { - TCL_APPEND_RESULT(interp, - "error reading data, expected height width ptr", - (char *)NULL); - return TCL_ERROR; - } - buffer = (agg::int8u*)pdata; - - /* get array mode (0=mono, 1=rgb, 2=rgba) */ - mode = atol(argv[3]); - if ((mode != 0) && (mode != 1) && (mode != 2)) { - TCL_APPEND_RESULT(interp, "illegal image mode", (char *)NULL); - return TCL_ERROR; - } - - /* check for bbox/blitting */ - bbox_parse = sscanf(argv[4], BBOX_FORMAT, &x1, &x2, &y1, &y2); - if (bbox_parse == 4) { - has_bbox = true; - } - else if ((bbox_parse == 1) && (x1 == 0)){ - has_bbox = false; - } else { - TCL_APPEND_RESULT(interp, "illegal bbox", (char *)NULL); - return TCL_ERROR; - } - - if (has_bbox) { - int srcstride = wdata * 4; - destx = (int)x1; - desty = (int)(hdata - y2); - destwidth = (int)(x2 - x1); - destheight = (int)(y2 - y1); - deststride = 4 * destwidth; - - try { - destbuffer = new agg::int8u[deststride * destheight]; - } - catch (const std::bad_alloc &) { - TCL_APPEND_RESULT(interp, "could not allocate memory", (char *)NULL); - return TCL_ERROR; - } - - for (int i = 0; i < destheight; ++i) { - memcpy(destbuffer + (deststride * i), - &buffer[(i + desty) * srcstride + (destx * 4)], - deststride); - } - } else { - destbuffer = NULL; - destx = desty = destwidth = destheight = deststride = 0; - } - - /* setup tkblock */ - block.pixelSize = 1; - if (mode == 0) { - block.offset[0] = block.offset[1] = block.offset[2] = 0; - nval = 1; - } else { - block.offset[0] = 0; - block.offset[1] = 1; - block.offset[2] = 2; - if (mode == 1) { - block.offset[3] = 0; - block.pixelSize = 3; - nval = 3; - } else { - block.offset[3] = 3; - block.pixelSize = 4; - nval = 4; - } - } - - if (has_bbox) { - block.width = destwidth; - block.height = destheight; - block.pitch = deststride; - block.pixelPtr = destbuffer; - - TK_PHOTO_PUT_BLOCK_NO_COMPOSITE(photo, &block, destx, desty, - destwidth, destheight); - delete[] destbuffer; - - } else { - block.width = wdata; - block.height = hdata; - block.pitch = (int)block.width * nval; - block.pixelPtr = buffer; - - /* Clear current contents */ - TK_PHOTO_BLANK(photo); - /* Copy opaque block to photo image, and leave the rest to TK */ - TK_PHOTO_PUT_BLOCK_NO_COMPOSITE(photo, &block, 0, 0, block.width, - block.height); - } - - return TCL_OK; -} - -static PyObject *_tkinit(PyObject *self, PyObject *args) -{ - Tcl_Interp *interp; - TkappObject *app; - - PyObject *arg; - int is_interp; - if (!PyArg_ParseTuple(args, "Oi", &arg, &is_interp)) { - return NULL; - } - - if (is_interp) { - interp = (Tcl_Interp *)PyLong_AsVoidPtr(arg); - } else { - /* Do it the hard way. This will break if the TkappObject - layout changes */ - app = (TkappObject *)arg; - interp = app->interp; - } - - /* This will bomb if interp is invalid... */ - - TCL_CREATE_COMMAND(interp, - "PyAggImagePhoto", - (Tcl_CmdProc *)PyAggImagePhoto, - (ClientData)0, - (Tcl_CmdDeleteProc *)NULL); - - Py_INCREF(Py_None); - return Py_None; -} - static PyObject *mpl_tk_blit(PyObject *self, PyObject *args) { Tcl_Interp *interp; @@ -279,7 +114,6 @@ Win32_SetForegroundWindow(PyObject *module, PyObject *args) static PyMethodDef functions[] = { /* Tkinter interface stuff */ - { "tkinit", (PyCFunction)_tkinit, METH_VARARGS }, { "blit", (PyCFunction)mpl_tk_blit, METH_VARARGS }, #ifdef _WIN32 { "Win32_GetForegroundWindow", (PyCFunction)Win32_GetForegroundWindow, METH_VARARGS },