From 70909c4d9dcaa287e57b90cb24278e5f016992ce Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 16:59:11 -0800 Subject: [PATCH 1/9] Cleanup: use `sorted()` whereever possible. --- doc/sphinxext/math_symbol_table.py | 8 +-- doc/utils/pylab_names.py | 10 +-- examples/pylab_examples/font_table_ttf.py | 3 +- .../style_sheets/style_sheets_reference.py | 7 +-- lib/matplotlib/__init__.py | 4 +- lib/matplotlib/axes/_base.py | 27 ++++---- lib/matplotlib/axis.py | 62 ++++++++----------- lib/matplotlib/backend_bases.py | 12 ++-- lib/matplotlib/backends/backend_gdk.py | 5 +- lib/matplotlib/backends/backend_gtk.py | 23 ++++--- lib/matplotlib/backends/backend_gtk3.py | 3 +- lib/matplotlib/backends/backend_qt5.py | 3 +- lib/matplotlib/backends/backend_svg.py | 6 +- lib/matplotlib/backends/backend_tkagg.py | 26 +++----- lib/matplotlib/cbook.py | 3 +- lib/matplotlib/colors.py | 7 +-- lib/matplotlib/figure.py | 37 +++-------- lib/matplotlib/image.py | 8 +-- lib/matplotlib/lines.py | 11 +--- lib/matplotlib/mlab.py | 31 ++++------ lib/matplotlib/patches.py | 21 +++---- lib/matplotlib/projections/__init__.py | 4 +- lib/matplotlib/pyplot.py | 9 +-- lib/matplotlib/scale.py | 4 +- lib/matplotlib/spines.py | 16 ++--- lib/matplotlib/table.py | 18 ++---- lib/matplotlib/tests/test_png.py | 3 +- lib/matplotlib/text.py | 9 +-- lib/mpl_toolkits/gtktools.py | 8 +-- lib/mpl_toolkits/mplot3d/art3d.py | 10 +-- lib/mpl_toolkits/mplot3d/axes3d.py | 29 ++++----- 31 files changed, 149 insertions(+), 278 deletions(-) diff --git a/doc/sphinxext/math_symbol_table.py b/doc/sphinxext/math_symbol_table.py index d0edb7c4b1ae..cf8b82e290c5 100644 --- a/doc/sphinxext/math_symbol_table.py +++ b/doc/sphinxext/math_symbol_table.py @@ -106,14 +106,10 @@ def get_n(n, l): lines = [] for category, columns, syms in symbols: - syms = syms.split() - syms.sort() + syms = sorted(syms.split()) lines.append("**%s**" % category) lines.append('') - max_width = 0 - for sym in syms: - max_width = max(max_width, len(sym)) - max_width = max_width * 2 + 16 + max_width = max(map(len, syms)) * 2 + 16 header = " " + (('=' * max_width) + ' ') * columns format = '%%%ds' % max_width for chunk in get_n(20, get_n(columns, syms)): diff --git a/doc/utils/pylab_names.py b/doc/utils/pylab_names.py index 164a077bc5e2..51348f1abbd7 100644 --- a/doc/utils/pylab_names.py +++ b/doc/utils/pylab_names.py @@ -4,11 +4,9 @@ """ from pylab import * d = locals() -keys = d.keys() -keys.sort() modd = dict() -for k in keys: +for k in sorted(d): o = d[k] if not callable(o): continue @@ -37,10 +35,8 @@ mod, k, doc = mod.strip(), k.strip(), doc.strip()[:80] modd.setdefault(mod, []).append((k, doc)) -mods = modd.keys() -mods.sort() -for mod in mods: - border = '*'*len(mod) +for mod in sorted(modd): + border = '*' * len(mod) print(mod) print(border) diff --git a/examples/pylab_examples/font_table_ttf.py b/examples/pylab_examples/font_table_ttf.py index b59ca990bb33..803e365f2d43 100755 --- a/examples/pylab_examples/font_table_ttf.py +++ b/examples/pylab_examples/font_table_ttf.py @@ -32,8 +32,7 @@ 'fonts', 'ttf', 'DejaVuSans.ttf') font = FT2Font(fontname) -codes = list(font.get_charmap().items()) -codes.sort() +codes = sorted(font.get_charmap().items()) # a 16,16 array of character strings chars = [['' for c in range(16)] for r in range(16)] diff --git a/examples/style_sheets/style_sheets_reference.py b/examples/style_sheets/style_sheets_reference.py index 1f67fd6b67ab..da4e21b17c62 100644 --- a/examples/style_sheets/style_sheets_reference.py +++ b/examples/style_sheets/style_sheets_reference.py @@ -135,11 +135,8 @@ def plot_figure(style_label=""): # Setup a list of all available styles, in alphabetical order but # the `default` and `classic` ones, which will be forced resp. in # first and second position. - style_list = list(plt.style.available) # *new* list: avoids side effects. - style_list.remove('classic') # `classic` is in the list: first remove it. - style_list.sort() - style_list.insert(0, u'default') - style_list.insert(1, u'classic') + style_list = ['default', 'classic'] + sorted( + style for style in plt.style.available if style != 'classic') # Plot a demonstration figure for every available style sheet. for style_label in style_list: diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 41301f37e47e..789d6aedf62d 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -968,9 +968,7 @@ def keys(self): """ Return sorted list of keys. """ - k = list(dict.keys(self)) - k.sort() - return k + return sorted(self) def values(self): """ diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 669f72030f7a..767d453a4f16 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -2365,36 +2365,35 @@ def draw(self, renderer=None, inframe=False): artists.remove(self._left_title) artists.remove(self._right_title) - if self.figure.canvas.is_saving(): - dsu = [(a.zorder, a) for a in artists] - else: - dsu = [(a.zorder, a) for a in artists - if (not a.get_animated() or a in self.images)] - - dsu.sort(key=itemgetter(0)) + if not self.figure.canvas.is_saving(): + artists = [a for a in artists + if not a.get_animated() or a in self.images] + artists = sorted(artists, key=lambda artist: artist.get_zorder()) # rasterize artists with negative zorder # if the minimum zorder is negative, start rasterization rasterization_zorder = self._rasterization_zorder if (rasterization_zorder is not None and - len(dsu) > 0 and dsu[0][0] < rasterization_zorder): + artists and artists[0].get_zorder() < rasterization_zorder): renderer.start_rasterizing() - dsu_rasterized = [l for l in dsu if l[0] < rasterization_zorder] - dsu = [l for l in dsu if l[0] >= rasterization_zorder] + artists_rasterized = [a for a in artists + if a.get_zorder() < rasterization_zorder] + artists = [a for a in artists + if a.get_zorder() >= rasterization_zorder] else: - dsu_rasterized = [] + artists_rasterized = [] # the patch draws the background rectangle -- the frame below # will draw the edges if self.axison and self._frameon: self.patch.draw(renderer) - if dsu_rasterized: - for zorder, a in dsu_rasterized: + if artists_rasterized: + for a in artists_rasterized: a.draw(renderer) renderer.stop_rasterizing() - mimage._draw_list_compositing_images(renderer, self, dsu) + mimage._draw_list_compositing_images(renderer, self, artists) renderer.close_group('axes') self._cachedRenderer = renderer diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 7c59b1764a3c..60dcdb9821ca 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -951,45 +951,37 @@ def _update_ticks(self, renderer): """ interval = self.get_view_interval() - tick_tups = [t for t in self.iter_ticks()] + tick_tups = list(self.iter_ticks()) if self._smart_bounds: # handle inverted limits - view_low, view_high = min(*interval), max(*interval) - data_low, data_high = self.get_data_interval() - if data_low > data_high: - data_low, data_high = data_high, data_low - locs = [ti[1] for ti in tick_tups] - locs.sort() - locs = np.array(locs) - if len(locs): - if data_low <= view_low: - # data extends beyond view, take view as limit - ilow = view_low + view_low, view_high = min(interval), max(interval) + data_low, data_high = sorted(self.get_data_interval()) + locs = np.sort([ti[1] for ti in tick_tups]) + if data_low <= view_low: + # data extends beyond view, take view as limit + ilow = view_low + else: + # data stops within view, take best tick + good_locs = locs[locs <= data_low] + if len(good_locs) > 0: + # last tick prior or equal to first data point + ilow = good_locs[-1] else: - # data stops within view, take best tick - cond = locs <= data_low - good_locs = locs[cond] - if len(good_locs) > 0: - # last tick prior or equal to first data point - ilow = good_locs[-1] - else: - # No ticks (why not?), take first tick - ilow = locs[0] - if data_high >= view_high: - # data extends beyond view, take view as limit - ihigh = view_high + # No ticks (why not?), take first tick + ilow = locs[0] + if data_high >= view_high: + # data extends beyond view, take view as limit + ihigh = view_high + else: + # data stops within view, take best tick + good_locs = locs[locs >= data_high] + if len(good_locs) > 0: + # first tick after or equal to last data point + ihigh = good_locs[0] else: - # data stops within view, take best tick - cond = locs >= data_high - good_locs = locs[cond] - if len(good_locs) > 0: - # first tick after or equal to last data point - ihigh = good_locs[0] - else: - # No ticks (why not?), take last tick - ihigh = locs[-1] - tick_tups = [ti for ti in tick_tups - if (ti[1] >= ilow) and (ti[1] <= ihigh)] + # No ticks (why not?), take last tick + ihigh = locs[-1] + tick_tups = [ti for ti in tick_tups if ilow <= ti[1] <= ihigh] # so that we don't lose ticks on the end, expand out the interval ever # so slightly. The "ever so slightly" is defined to be the width of a diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index f17c31e31a77..2b6f5c72b484 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -1469,15 +1469,12 @@ def __init__(self, name, canvas, x, y, guiEvent=None): else: axes_list = [self.canvas.mouse_grabber] - if len(axes_list) == 0: # None found + if axes_list: # Use highest zorder. + self.inaxes = max(axes_list, key=lambda x: x.zorder) + else: # None found. self.inaxes = None self._update_enter_leave() return - elif (len(axes_list) > 1): # Overlap, get the highest zorder - axes_list.sort(key=lambda x: x.zorder) - self.inaxes = axes_list[-1] # Use the highest zorder - else: # Just found one hit - self.inaxes = axes_list[0] try: trans = self.inaxes.transData.inverted() @@ -1751,8 +1748,7 @@ def onRemove(self, ev): canvas.mpl_connect('mouse_press_event',canvas.onRemove) """ # Find the top artist under the cursor - under = self.figure.hitlist(ev) - under.sort(key=lambda x: x.zorder) + under = sorted(self.figure.hitlist(ev), key=lambda x: x.zorder) h = None if under: h = under[-1] diff --git a/lib/matplotlib/backends/backend_gdk.py b/lib/matplotlib/backends/backend_gdk.py index d750a09f01a0..2b60faa76f2e 100644 --- a/lib/matplotlib/backends/backend_gdk.py +++ b/lib/matplotlib/backends/backend_gdk.py @@ -36,9 +36,8 @@ def fn_name(): return sys._getframe(1).f_code.co_name _debug = False # Image formats that this backend supports - for FileChooser and print_figure() -IMAGE_FORMAT = ['eps', 'jpg', 'png', 'ps', 'svg'] + ['bmp'] # , 'raw', 'rgb'] -IMAGE_FORMAT.sort() -IMAGE_FORMAT_DEFAULT = 'png' +IMAGE_FORMAT = sorted(['eps', 'jpg', 'png', 'ps', 'svg'] + ['bmp']) # , 'raw', 'rgb'] +IMAGE_FORMAT_DEFAULT = 'png' class RendererGDK(RendererBase): diff --git a/lib/matplotlib/backends/backend_gtk.py b/lib/matplotlib/backends/backend_gtk.py index 368eef94cb5d..f2a28b8afff8 100644 --- a/lib/matplotlib/backends/backend_gtk.py +++ b/lib/matplotlib/backends/backend_gtk.py @@ -829,33 +829,32 @@ def __init__ (self, filetypes = [], default_filetype = None ): - super(FileChooserDialog, self).__init__ (title, parent, action, - buttons) + super(FileChooserDialog, self).__init__(title, parent, action, buttons) super(FileChooserDialog, self).set_do_overwrite_confirmation(True) - self.set_default_response (gtk.RESPONSE_OK) + self.set_default_response(gtk.RESPONSE_OK) - if not path: path = os.getcwd() + os.sep + if not path: + path = os.getcwd() + os.sep # create an extra widget to list supported image formats self.set_current_folder (path) self.set_current_name ('image.' + default_filetype) - hbox = gtk.HBox (spacing=10) - hbox.pack_start (gtk.Label ("File Format:"), expand=False) + hbox = gtk.HBox(spacing=10) + hbox.pack_start(gtk.Label ("File Format:"), expand=False) liststore = gtk.ListStore(gobject.TYPE_STRING) cbox = gtk.ComboBox(liststore) cell = gtk.CellRendererText() cbox.pack_start(cell, True) cbox.add_attribute(cell, 'text', 0) - hbox.pack_start (cbox) + hbox.pack_start(cbox) self.filetypes = filetypes - self.sorted_filetypes = list(six.iteritems(filetypes)) - self.sorted_filetypes.sort() + self.sorted_filetypes = sorted(six.iteritems(filetypes)) default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): - cbox.append_text ("%s (*.%s)" % (name, ext)) + cbox.append_text("%s (*.%s)" % (name, ext)) if ext == default_filetype: default = i cbox.set_active(default) @@ -874,8 +873,8 @@ def cb_cbox_changed (cbox, data=None): elif ext == '': filename = filename.rstrip('.') + '.' + new_ext - self.set_current_name (filename) - cbox.connect ("changed", cb_cbox_changed) + self.set_current_name(filename) + cbox.connect("changed", cb_cbox_changed) hbox.show_all() self.set_extra_widget(hbox) diff --git a/lib/matplotlib/backends/backend_gtk3.py b/lib/matplotlib/backends/backend_gtk3.py index 4243739a8036..38b871d48518 100644 --- a/lib/matplotlib/backends/backend_gtk3.py +++ b/lib/matplotlib/backends/backend_gtk3.py @@ -695,8 +695,7 @@ def __init__ (self, hbox.pack_start(cbox, False, False, 0) self.filetypes = filetypes - self.sorted_filetypes = list(six.iteritems(filetypes)) - self.sorted_filetypes.sort() + self.sorted_filetypes = sorted(six.iteritems(filetypes)) default = 0 for i, (ext, name) in enumerate(self.sorted_filetypes): liststore.append(["%s (*.%s)" % (name, ext)]) diff --git a/lib/matplotlib/backends/backend_qt5.py b/lib/matplotlib/backends/backend_qt5.py index de16c9a50414..6f77ea5e1e56 100644 --- a/lib/matplotlib/backends/backend_qt5.py +++ b/lib/matplotlib/backends/backend_qt5.py @@ -719,8 +719,7 @@ def configure_subplots(self): def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() - sorted_filetypes = list(six.iteritems(filetypes)) - sorted_filetypes.sort() + sorted_filetypes = sorted(six.iteritems(filetypes)) default_filetype = self.canvas.get_default_filetype() startpath = matplotlib.rcParams.get('savefig.directory', '') diff --git a/lib/matplotlib/backends/backend_svg.py b/lib/matplotlib/backends/backend_svg.py index cb1c09460293..4d5079257673 100644 --- a/lib/matplotlib/backends/backend_svg.py +++ b/lib/matplotlib/backends/backend_svg.py @@ -145,8 +145,7 @@ def start(self, tag, attrib={}, **extra): if attrib or extra: attrib = attrib.copy() attrib.update(extra) - attrib = list(six.iteritems(attrib)) - attrib.sort() + attrib = sorted(six.iteritems(attrib)) for k, v in attrib: if not v == '': k = escape_cdata(k) @@ -248,8 +247,7 @@ def generate_transform(transform_list=[]): def generate_css(attrib={}): if attrib: output = io.StringIO() - attrib = list(six.iteritems(attrib)) - attrib.sort() + attrib = sorted(six.iteritems(attrib)) for k, v in attrib: k = escape_attrib(k) v = escape_attrib(v) diff --git a/lib/matplotlib/backends/backend_tkagg.py b/lib/matplotlib/backends/backend_tkagg.py index bd0c67e8bb9f..b2d0ef5f11ea 100644 --- a/lib/matplotlib/backends/backend_tkagg.py +++ b/lib/matplotlib/backends/backend_tkagg.py @@ -807,15 +807,10 @@ def save_figure(self, *args): # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first - default_filetype_name = filetypes[default_filetype] - del filetypes[default_filetype] - - sorted_filetypes = list(six.iteritems(filetypes)) - sorted_filetypes.sort() - sorted_filetypes.insert(0, (default_filetype, default_filetype_name)) - - tk_filetypes = [ - (name, '*.%s' % ext) for (ext, name) in sorted_filetypes] + default_filetype_name = filetypes.pop(default_filetype) + sorted_filetypes = ([(default_filetype, default_filetype_name)] + + sorted(six.iteritems(filetypes))) + tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes] # adding a default extension seems to break the # asksaveasfilename dialog when you choose various save types @@ -1047,15 +1042,10 @@ def trigger(self, *args): # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first - default_filetype_name = filetypes[default_filetype] - del filetypes[default_filetype] - - sorted_filetypes = list(six.iteritems(filetypes)) - sorted_filetypes.sort() - sorted_filetypes.insert(0, (default_filetype, default_filetype_name)) - - tk_filetypes = [ - (name, '*.%s' % ext) for (ext, name) in sorted_filetypes] + default_filetype_name = filetypes.pop(default_filetype) + sorted_filetypes = ([(default_filetype, default_filetype_name)] + + sorted(six.iteritems(filetypes))) + tk_filetypes = [(name, '*.%s' % ext) for ext, name in sorted_filetypes] # adding a default extension seems to break the # asksaveasfilename dialog when you choose various save types diff --git a/lib/matplotlib/cbook.py b/lib/matplotlib/cbook.py index 1e2fe5e739ae..11988093932b 100644 --- a/lib/matplotlib/cbook.py +++ b/lib/matplotlib/cbook.py @@ -903,8 +903,7 @@ def byItem(self, data, itemindex=None, inplace=1): data.sort() result = data else: - result = data[:] - result.sort() + result = sorted(data) return result else: aux = [(data[i][itemindex], i) for i in range(len(data))] diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index f1d5a357695d..9acd52a658e5 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -372,10 +372,9 @@ def makeMappingArray(N, data, gamma=1.0): if x[0] != 0. or x[-1] != 1.0: raise ValueError( - "data mapping points must start with x=0. and end with x=1") - if np.sometrue(np.sort(x) - x): - raise ValueError( - "data mapping points must have x in increasing order") + "data mapping points must start with x=0 and end with x=1") + if (np.diff(x) < 0).any(): + raise ValueError("data mapping points must have x in increasing order") # begin generation of lookup table x = x * (N - 1) lut = np.zeros((N,), float) diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 26faffa6d77f..9745a4ae2510 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -17,7 +17,6 @@ import six import warnings -from operator import itemgetter import numpy as np @@ -1220,34 +1219,12 @@ def draw(self, renderer): if not self.get_visible(): return - # a list of (zorder, func_to_call, list_of_args) - dsu = [] - - for a in self.patches: - dsu.append((a.get_zorder(), a)) - - for a in self.lines: - dsu.append((a.get_zorder(), a)) - - for a in self.artists: - dsu.append((a.get_zorder(), a)) - - for a in self.images: - dsu.append((a.get_zorder(), a)) - - # render the axes - for a in self.axes: - dsu.append((a.get_zorder(), a)) - - # render the figure text - for a in self.texts: - dsu.append((a.get_zorder(), a)) - - for a in self.legends: - dsu.append((a.get_zorder(), a)) - - dsu = [row for row in dsu if not row[1].get_animated()] - dsu.sort(key=itemgetter(0)) + artists = sorted( + (artist for artist in (self.patches + self.lines + self.artists + + self.images + self.axes + self.texts + + self.legends) + if not artist.get_animated()), + key=lambda artist: artist.get_zorder()) try: renderer.open_group('figure') @@ -1262,7 +1239,7 @@ def draw(self, renderer): self.patch.draw(renderer) mimage._draw_list_compositing_images( - renderer, self, dsu, self.suppressComposite) + renderer, self, artists, self.suppressComposite) renderer.close_group('figure') finally: diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 1723db3041bf..dcc28a7009a7 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -118,7 +118,7 @@ def composite_images(images, renderer, magnification=1.0): def _draw_list_compositing_images( - renderer, parent, dsu, suppress_composite=None): + renderer, parent, artists, suppress_composite=None): """ Draw a sorted list of artists, compositing images into a single image where possible. @@ -127,7 +127,7 @@ def _draw_list_compositing_images( between `Figure.draw` and `Axes.draw`, but otherwise should not be generally useful. """ - has_images = any(isinstance(x[1], _ImageBase) for x in dsu) + has_images = any(isinstance(x, _ImageBase) for x in artists) # override the renderer default if suppressComposite is not None not_composite = renderer.option_image_nocomposite() @@ -135,7 +135,7 @@ def _draw_list_compositing_images( not_composite = suppress_composite if not_composite or not has_images: - for zorder, a in dsu: + for a in artists: a.draw(renderer) else: # Composite any adjacent images together @@ -156,7 +156,7 @@ def flush_images(): gc.restore() del image_group[:] - for zorder, a in dsu: + for a in artists: if isinstance(a, _ImageBase) and a.can_composite(): image_group.append(a) else: diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 5e9435a38ac2..25dd36fbc79d 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -1519,15 +1519,8 @@ def onpick(self, event): """When the line is picked, update the set of selected indicies.""" if event.artist is not self.line: return - - for i in event.ind: - if i in self.ind: - self.ind.remove(i) - else: - self.ind.add(i) - - ind = list(self.ind) - ind.sort() + self.ind ^= set(event.ind) + ind = sorted(self.ind) xdata, ydata = self.line.get_data() self.process_selected(ind, xdata[ind], ydata[ind]) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 31d028661567..c950460e07fe 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -1730,31 +1730,27 @@ def _interpolate(a, b, fraction): """Returns the point at the given fraction between a and b, where 'fraction' must be between 0 and 1. """ - return a + (b - a)*fraction + return a + (b - a) * fraction - scalar = True - if cbook.iterable(p): - scalar = False per = np.array(p) - values = np.array(x).ravel() # copy - values.sort() + values = np.sort(x, axis=None) - idxs = per/100. * (values.shape[0] - 1) - ai = idxs.astype(np.int) + idxs = per / 100 * (values.shape[0] - 1) + ai = idxs.astype(int) bi = ai + 1 frac = idxs % 1 # handle cases where attempting to interpolate past last index cond = bi >= len(values) - if scalar: + if per.ndim: + ai[cond] -= 1 + bi[cond] -= 1 + frac[cond] += 1 + else: if cond: ai -= 1 bi -= 1 frac += 1 - else: - ai[cond] -= 1 - bi[cond] -= 1 - frac[cond] += 1 return _interpolate(values[ai], values[bi], frac) @@ -2413,17 +2409,14 @@ def rec_groupby(r, groupby, stats): """ # build a dictionary from groupby keys-> list of indices into r with # those keys - rowd = dict() + rowd = {} for i, row in enumerate(r): key = tuple([row[attr] for attr in groupby]) rowd.setdefault(key, []).append(i) - # sort the output by groupby keys - keys = list(six.iterkeys(rowd)) - keys.sort() - rows = [] - for key in keys: + # sort the output by groupby keys + for key in sorted(rowd): row = list(key) # get the indices for this groupby key ind = rowd[key] diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 3cb49cb56887..8e85f89e3f26 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1670,13 +1670,9 @@ def iter_circle_intersect_on_line_seg(x0, y0, x1, y1): self.get_transform().inverted() box_path = box_path.transformed(box_path_transform) - PI = np.pi - TWOPI = PI * 2.0 - RAD2DEG = 180.0 / PI - DEG2RAD = PI / 180.0 theta1 = self.theta1 theta2 = self.theta2 - thetas = {} + thetas = set() # For each of the point pairs, there is a line segment for p0, p1 in zip(box_path.vertices[:-1], box_path.vertices[1:]): x0, y0 = p0 @@ -1684,18 +1680,15 @@ def iter_circle_intersect_on_line_seg(x0, y0, x1, y1): for x, y in iter_circle_intersect_on_line_seg(x0, y0, x1, y1): theta = np.arccos(x) if y < 0: - theta = TWOPI - theta + theta = 2 * np.pi - theta # Convert radians to angles - theta *= RAD2DEG - if theta > theta1 and theta < theta2: - thetas[theta] = None - - thetas = list(six.iterkeys(thetas)) - thetas.sort() - thetas.append(theta2) + theta = np.rad2deg(theta) + if theta1 < theta < theta2: + thetas.add(theta) + thetas = sorted(thetas) + [theta2] last_theta = theta1 - theta1_rad = theta1 * DEG2RAD + theta1_rad = np.deg2rad(theta1) inside = box_path.contains_point((np.cos(theta1_rad), np.sin(theta1_rad))) diff --git a/lib/matplotlib/projections/__init__.py b/lib/matplotlib/projections/__init__.py index 235598563931..fc47c95da9c8 100644 --- a/lib/matplotlib/projections/__init__.py +++ b/lib/matplotlib/projections/__init__.py @@ -33,9 +33,7 @@ def get_projection_names(self): Get a list of the names of all projections currently registered. """ - names = list(six.iterkeys(self._all_projection_types)) - names.sort() - return names + return sorted(self._all_projection_types) projection_registry = ProjectionRegistry() projection_registry.register( diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 534887362a81..f837db3bcdfb 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -591,9 +591,7 @@ def fignum_exists(num): def get_fignums(): """Return a list of existing figure numbers.""" - fignums = list(six.iterkeys(_pylab_helpers.Gcf.figs)) - fignums.sort() - return fignums + return sorted(_pylab_helpers.Gcf.figs) def get_figlabels(): @@ -1811,9 +1809,8 @@ def get_plot_commands(): if inspect.isfunction(obj) and inspect.getmodule(obj) is this_module: commands.add(name) - commands = list(commands) - commands.sort() - return commands + return sorted(commands) + def colors(): """ diff --git a/lib/matplotlib/scale.py b/lib/matplotlib/scale.py index ca0292e96377..17bc4e83fff1 100644 --- a/lib/matplotlib/scale.py +++ b/lib/matplotlib/scale.py @@ -519,9 +519,7 @@ def limit_range_for_scale(self, vmin, vmax, minpos): def get_scale_names(): - names = list(six.iterkeys(_scale_mapping)) - names.sort() - return names + return sorted(_scale_mapping) def scale_factory(scale, axis, **kwargs): diff --git a/lib/matplotlib/spines.py b/lib/matplotlib/spines.py index 20042d4ea314..339753043e9c 100644 --- a/lib/matplotlib/spines.py +++ b/lib/matplotlib/spines.py @@ -207,14 +207,9 @@ def _adjust_location(self): if self._smart_bounds: # attempt to set bounds in sophisticated way - if low > high: - # handle inverted limits - low, high = high, low - viewlim_low = low - viewlim_high = high - - del low, high + # handle inverted limits + viewlim_low, viewlim_high = sorted([low, high]) if self.spine_type in ('left', 'right'): datalim_low, datalim_high = self.axes.dataLim.intervaly @@ -223,11 +218,8 @@ def _adjust_location(self): datalim_low, datalim_high = self.axes.dataLim.intervalx ticks = self.axes.get_xticks() # handle inverted limits - ticks = list(ticks) - ticks.sort() - ticks = np.array(ticks) - if datalim_low > datalim_high: - datalim_low, datalim_high = datalim_high, datalim_low + ticks = np.sort(ticks) + datalim_low, datalim_high = sorted([datalim_low, datalim_high]) if datalim_low < viewlim_low: # Data extends past view. Clip line to view. diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index 6c69bab314e0..63b1988a5843 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -185,7 +185,7 @@ def visible_edges(self, value): msg = ('Invalid edge param {0}, must only be one of' ' {1} or string of {2}.').format( value, - ", ".join(self._edge_aliases.keys()), + ", ".join(self._edge_aliases), ", ".join(self._edges), ) raise ValueError(msg) @@ -317,12 +317,9 @@ def draw(self, renderer): renderer.open_group('table') self._update_positions(renderer) - keys = list(six.iterkeys(self._cells)) - keys.sort() - for key in keys: + for key in sorted(self._cells): self._cells[key].draw(renderer) - # for c in self._cells.itervalues(): - # c.draw(renderer) + renderer.close_group('table') self.stale = False @@ -386,18 +383,13 @@ def _do_cell_alignment(self): # work out left position for each column xpos = 0 lefts = {} - cols = list(six.iterkeys(widths)) - cols.sort() - for col in cols: + for col in sorted(widths): lefts[col] = xpos xpos += widths[col] ypos = 0 bottoms = {} - rows = list(six.iterkeys(heights)) - rows.sort() - rows.reverse() - for row in rows: + for row in sorted(heights, reverse=True): bottoms[row] = ypos ypos += heights[row] diff --git a/lib/matplotlib/tests/test_png.py b/lib/matplotlib/tests/test_png.py index 7f4d8297ea38..5dc3155f11e0 100644 --- a/lib/matplotlib/tests/test_png.py +++ b/lib/matplotlib/tests/test_png.py @@ -23,8 +23,7 @@ def test_pngsuite(): os.path.dirname(__file__), 'baseline_images', 'pngsuite') - files = glob.glob(os.path.join(dirname, 'basn*.png')) - files.sort() + files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png'))) fig = plt.figure(figsize=(len(files), 2)) diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index b9a00dc259bb..9e2d8be26842 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -2260,13 +2260,8 @@ def _update_position_xytext(self, renderer, xy_pixel): xpos = ((l, 0), (xc, 0.5), (r, 1)) ypos = ((b, 0), (yc, 0.5), (t, 1)) - dsu = [(abs(val[0] - x0), val) for val in xpos] - dsu.sort() - _, (x, relposx) = dsu[0] - - dsu = [(abs(val[0] - y0), val) for val in ypos] - dsu.sort() - _, (y, relposy) = dsu[0] + _, (x, relposx) = min((abs(val[0] - x0), val) for val in xpos) + _, (y, relposy) = min((abs(val[0] - y0), val) for val in ypos) self._arrow_relpos = (relposx, relposy) diff --git a/lib/mpl_toolkits/gtktools.py b/lib/mpl_toolkits/gtktools.py index f3e15d28cb4d..4067dfcdf4f2 100644 --- a/lib/mpl_toolkits/gtktools.py +++ b/lib/mpl_toolkits/gtktools.py @@ -402,19 +402,15 @@ def __init__(self, r, formatd=None, stringd=None): self.combod = dict() if len(stringd): types.extend([gobject.TYPE_INT]*len(stringd)) - - keys = list(six.iterkeys(stringd)) - keys.sort() - + keys = sorted(stringd) valid = set(r.dtype.names) for ikey, key in enumerate(keys): - assert(key in valid) + assert key in valid combostore = gtk.ListStore(gobject.TYPE_STRING) for s in stringd[key]: combostore.append([s]) self.combod[key] = combostore, len(self.headers)+ikey - gtk.ListStore.__init__(self, *types) for row in r: diff --git a/lib/mpl_toolkits/mplot3d/art3d.py b/lib/mpl_toolkits/mplot3d/art3d.py index 636075d54bf0..22b8416f5a4d 100644 --- a/lib/mpl_toolkits/mplot3d/art3d.py +++ b/lib/mpl_toolkits/mplot3d/art3d.py @@ -641,11 +641,11 @@ def do_3d_projection(self, renderer): # if required sort by depth (furthest drawn first) if self._zsort: - indices = range(len(xyzlist)) - z_segments_2d = [(self._zsortfunc(zs), list(zip(xs, ys)), fc, ec, - idx) for (xs, ys, zs), fc, ec, idx in - zip(xyzlist, cface, cedge, indices)] - z_segments_2d.sort(key=lambda x: x[0], reverse=True) + z_segments_2d = sorted( + ((self._zsortfunc(zs), list(zip(xs, ys)), fc, ec, idx) + for idx, ((xs, ys, zs), fc, ec) + in enumerate(zip(xyzlist, cface, cedge))), + key=lambda x: x[0], reverse=True) else: raise ValueError("whoops") diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index aee3f61055e7..00aa7741e460 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -16,7 +16,6 @@ from six.moves import map, xrange, zip, reduce import warnings -from operator import itemgetter import matplotlib.axes as maxes from matplotlib.axes import Axes, rcParams @@ -267,17 +266,17 @@ def draw(self, renderer): renderer.get_axis_position = self.get_axis_position # Calculate projection of collections and zorder them - zlist = [(col.do_3d_projection(renderer), col) \ - for col in self.collections] - zlist.sort(key=itemgetter(0), reverse=True) - for i, (z, col) in enumerate(zlist): + for i, col in enumerate( + sorted(self.collections, + key=lambda col: col.do_3d_projection(renderer), + reverse=True)): col.zorder = i # Calculate projection of patches and zorder them - zlist = [(patch.do_3d_projection(renderer), patch) \ - for patch in self.patches] - zlist.sort(key=itemgetter(0), reverse=True) - for i, (z, patch) in enumerate(zlist): + for i, patch in enumerate( + sorted(self.patches, + key=lambda patch: patch.do_3d_projection(renderer), + reverse=True)): patch.zorder = i if self._axis3don: @@ -1118,16 +1117,10 @@ def format_coord(self, xd, yd): return 'azimuth=%d deg, elevation=%d deg ' % (self.azim, self.elev) # ignore xd and yd and display angles instead - p = (xd, yd) - edges = self.tunit_edges() - #lines = [proj3d.line2d(p0,p1) for (p0,p1) in edges] - ldists = [(proj3d.line2d_seg_dist(p0, p1, p), i) for \ - i, (p0, p1) in enumerate(edges)] - ldists.sort() # nearest edge - edgei = ldists[0][1] - - p0, p1 = edges[edgei] + p0, p1 = min(self.tunit_edges(), + key=lambda edge: proj3d.line2d_seg_dist( + edge[0], edge[1], (xd, yd))) # scale the z value to match x0, y0, z0 = p0 From 7a83fc426f689f15df812676dc36d003f7d39a9a Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 19:45:01 -0800 Subject: [PATCH 2/9] Iterating over a dict is easy. --- lib/matplotlib/__init__.py | 2 +- lib/matplotlib/artist.py | 6 +----- lib/matplotlib/axes/_base.py | 11 ++++------- lib/matplotlib/backends/backend_pdf.py | 2 +- lib/matplotlib/backends/backend_ps.py | 4 ++-- lib/matplotlib/backends/backend_svg.py | 6 ++---- lib/matplotlib/cbook.py | 8 +++----- lib/matplotlib/cm.py | 11 ++++------- lib/matplotlib/dviread.py | 2 +- lib/matplotlib/font_manager.py | 8 ++------ lib/matplotlib/image.py | 4 ++-- lib/matplotlib/legend.py | 6 ++---- lib/matplotlib/lines.py | 3 +-- lib/matplotlib/mathtext.py | 8 ++++---- lib/matplotlib/mlab.py | 2 +- lib/matplotlib/offsetbox.py | 18 +++++++----------- lib/matplotlib/path.py | 4 +--- lib/matplotlib/table.py | 11 +++++------ lib/matplotlib/testing/compare.py | 2 +- lib/matplotlib/tests/test_colors.py | 2 +- lib/matplotlib/tests/test_rcparams.py | 4 ++-- 21 files changed, 48 insertions(+), 76 deletions(-) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 789d6aedf62d..1bdab1dc8069 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -1894,4 +1894,4 @@ def inner(ax, *args, **kwargs): verbose.report('verbose.level %s' % verbose.level) verbose.report('interactive is %s' % is_interactive()) verbose.report('platform is %s' % sys.platform) -verbose.report('loaded modules: %s' % six.iterkeys(sys.modules), 'debug') +verbose.report('loaded modules: %s' % list(sys.modules), 'debug') diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index 972ca89b8e4c..3c027625cecc 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -1317,12 +1317,8 @@ def pprint_getters(self): Return the getters and actual values as list of strings. """ - d = self.properties() - names = list(six.iterkeys(d)) - names.sort() lines = [] - for name in names: - val = d[name] + for name, val in sorted(six.iteritems(self.properties())): if getattr(val, 'shape', ()) != () and len(val) > 6: s = str(val[:6]) + '...' else: diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 767d453a4f16..7bb675a497b5 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1332,12 +1332,11 @@ def set_anchor(self, anchor): ===== ============ """ - if (anchor in list(six.iterkeys(mtransforms.Bbox.coefs)) or - len(anchor) == 2): + if anchor in mtransforms.Bbox.coefs or len(anchor) == 2: self._anchor = anchor else: raise ValueError('argument must be among %s' % - ', '.join(six.iterkeys(mtransforms.Bbox.coefs))) + ', '.join(mtransforms.Bbox.coefs)) self.stale = True def get_data_ratio(self): @@ -2877,8 +2876,7 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw): if 'xmax' in kw: right = kw.pop('xmax') if kw: - raise ValueError("unrecognized kwargs: %s" % - list(six.iterkeys(kw))) + raise ValueError("unrecognized kwargs: %s" % list(kw)) if right is None and iterable(left): left, right = left @@ -3158,8 +3156,7 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw): if 'ymax' in kw: top = kw.pop('ymax') if kw: - raise ValueError("unrecognized kwargs: %s" % - list(six.iterkeys(kw))) + raise ValueError("unrecognized kwargs: %s" % list(kw)) if top is None and iterable(bottom): bottom, top = bottom diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 4a95ffe09f88..16c5e52319b4 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -1533,7 +1533,7 @@ def is_date(x): 'CreationDate': is_date, 'ModDate': is_date, 'Trapped': check_trapped} - for k in six.iterkeys(self.infoDict): + for k in self.infoDict: if k not in keywords: warnings.warn('Unknown infodict keyword: %s' % k) else: diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 56bcbb5e5296..e0c823b9b271 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -958,8 +958,8 @@ def _print_ps(self, outfile, format, *args, **kwargs): if papertype == 'auto': pass elif papertype not in papersize: - raise RuntimeError( '%s is not a valid papertype. Use one \ - of %s'% (papertype, ', '.join(six.iterkeys(papersize)))) + raise RuntimeError('%s is not a valid papertype. Use one of %s' % + (papertype, ', '.join(papersize))) orientation = kwargs.pop("orientation", "portrait").lower() if orientation == 'landscape': isLandscape = True diff --git a/lib/matplotlib/backends/backend_svg.py b/lib/matplotlib/backends/backend_svg.py index 4d5079257673..4f6785b7fdc8 100644 --- a/lib/matplotlib/backends/backend_svg.py +++ b/lib/matplotlib/backends/backend_svg.py @@ -593,10 +593,8 @@ 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) - for key in list(six.iterkeys(style)): - if not key.startswith('stroke'): - del style[key] - style = generate_css(style) + style = generate_css({k: v for k, v in six.iteritems(style) + if k.startswith('stroke')}) if oid is None: oid = self._make_id('m', dictkey) diff --git a/lib/matplotlib/cbook.py b/lib/matplotlib/cbook.py index 11988093932b..8afba839344b 100644 --- a/lib/matplotlib/cbook.py +++ b/lib/matplotlib/cbook.py @@ -668,10 +668,8 @@ def __init__(self, **kwds): self.__dict__.update(kwds) def __repr__(self): - keys = six.iterkeys(self.__dict__) - return 'Bunch(%s)' % ', '.join(['%s=%s' % (k, self.__dict__[k]) - for k - in keys]) + return 'Bunch(%s)' % ', '.join( + '%s=%s' % kv for kv in six.iteritems(vars(self))) @deprecated('2.1') @@ -940,7 +938,7 @@ class Xlator(dict): def _make_regex(self): """ Build re object based on the keys of the current dictionary """ - return re.compile("|".join(map(re.escape, list(six.iterkeys(self))))) + return re.compile("|".join(map(re.escape, self))) def __call__(self, match): """ Handler invoked for each regex *match* """ diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 60d8c44eb700..7c1fac5d5d20 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -86,16 +86,13 @@ def _generate_cmap(name, lutsize): with _warnings.catch_warnings(): _warnings.simplefilter("ignore") # Generate the reversed specifications ... - for cmapname in list(six.iterkeys(datad)): - spec = datad[cmapname] - spec_reversed = _reverse_cmap_spec(spec) - datad[cmapname + '_r'] = spec_reversed + for cmapname, spec in list(six.iteritems(datad)): + datad[cmapname + '_r'] = _reverse_cmap_spec(spec) # Precache the cmaps with ``lutsize = LUTSIZE`` ... - # Use datad.keys() to also add the reversed ones added in the section - # above: - for cmapname in six.iterkeys(datad): + # Also add the reversed ones added in the section above: + for cmapname in datad: cmap_d[cmapname] = _generate_cmap(cmapname, LUTSIZE) cmap_d.update(cmaps_listed) diff --git a/lib/matplotlib/dviread.py b/lib/matplotlib/dviread.py index 7a2a428f167e..78ca76884ac5 100644 --- a/lib/matplotlib/dviread.py +++ b/lib/matplotlib/dviread.py @@ -532,7 +532,7 @@ def __init__(self, scale, tfm, texname, vf): scale, tfm, texname, vf self.size = scale * (72.0 / (72.27 * 2**16)) try: - nchars = max(six.iterkeys(tfm.width)) + 1 + nchars = max(tfm.width) + 1 except ValueError: nchars = 0 self.widths = [(1000*tfm.width.get(char, 0)) >> 20 diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index db31e4d5960a..edbb055918ea 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -247,7 +247,7 @@ def win32InstalledFonts(directory=None, fontext='ttf'): continue except MemoryError: continue - return list(six.iterkeys(items)) + return list(items) finally: winreg.CloseKey(local) return None @@ -439,11 +439,7 @@ def ttfFontProperty(font): # 600 (semibold, demibold), 700 (bold), 800 (heavy), 900 (black) # lighter and bolder are also allowed. - weight = None - for w in six.iterkeys(weight_dict): - if sfnt4.find(w) >= 0: - weight = w - break + weight = next((w for w in weight_dict if sfnt4.find(w) >= 0), None) if not weight: if font.style_flags & ft2font.BOLD: weight = 700 diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index dcc28a7009a7..32696d035b90 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -56,7 +56,7 @@ 'blackman': _image.BLACKMAN, } -interpolations_names = set(six.iterkeys(_interpd_)) +interpolations_names = set(_interpd_) def composite_images(images, renderer, magnification=1.0): @@ -1224,7 +1224,7 @@ def pilread(fname): if im is None: raise ValueError('Only know how to handle extensions: %s; ' 'with Pillow installed matplotlib can handle ' - 'more images' % list(six.iterkeys(handlers))) + 'more images' % list(handlers)) return im handler = handlers[ext] diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index e68427e0c159..b940a6b0c5ea 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -323,15 +323,13 @@ def __init__(self, parent, handles, labels, if self.isaxes: warnings.warn('Unrecognized location "%s". Falling back ' 'on "best"; valid locations are\n\t%s\n' - % (loc, '\n\t'.join( - six.iterkeys(self.codes)))) + % (loc, '\n\t'.join(self.codes))) loc = 0 else: warnings.warn('Unrecognized location "%s". Falling back ' 'on "upper right"; ' 'valid locations are\n\t%s\n' - % (loc, '\n\t'.join( - six.iterkeys(self.codes)))) + % (loc, '\n\t'.join(self.codes))) loc = 1 else: loc = self.codes[loc] diff --git a/lib/matplotlib/lines.py b/lib/matplotlib/lines.py index 25dd36fbc79d..7946a6bd847b 100644 --- a/lib/matplotlib/lines.py +++ b/lib/matplotlib/lines.py @@ -264,8 +264,7 @@ class Line2D(Artist): drawStyles.update(_drawStyles_l) drawStyles.update(_drawStyles_s) # Need a list ordered with long names first: - drawStyleKeys = (list(six.iterkeys(_drawStyles_l)) + - list(six.iterkeys(_drawStyles_s))) + drawStyleKeys = list(_drawStyles_l) + list(_drawStyles_s) # Referenced here to maintain API. These are defined in # MarkerStyle diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index 5a0923592581..b24a1b030406 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -2358,7 +2358,7 @@ def __init__(self): p.rbracket <<= Literal(']').suppress() p.bslash <<= Literal('\\') - p.space <<= oneOf(list(six.iterkeys(self._space_widths))) + p.space <<= oneOf(list(self._space_widths)) p.customspace <<= (Suppress(Literal(r'\hspace')) - ((p.lbrace + p.float_literal + p.rbrace) | Error(r"Expected \hspace{n}"))) @@ -2367,17 +2367,17 @@ def __init__(self): p.single_symbol <<= Regex(r"([a-zA-Z0-9 +\-*/<>=:,.;!\?&'@()\[\]|%s])|(\\[%%${}\[\]_|])" % unicode_range) p.snowflake <<= Suppress(p.bslash) + oneOf(self._snowflake) - p.symbol_name <<= (Combine(p.bslash + oneOf(list(six.iterkeys(tex2uni)))) + + p.symbol_name <<= (Combine(p.bslash + oneOf(list(tex2uni))) + FollowedBy(Regex("[^A-Za-z]").leaveWhitespace() | StringEnd())) p.symbol <<= (p.single_symbol | p.symbol_name).leaveWhitespace() p.apostrophe <<= Regex("'+") - p.c_over_c <<= Suppress(p.bslash) + oneOf(list(six.iterkeys(self._char_over_chars))) + p.c_over_c <<= Suppress(p.bslash) + oneOf(list(self._char_over_chars)) p.accent <<= Group( Suppress(p.bslash) - + oneOf(list(six.iterkeys(self._accent_map)) + list(self._wide_accents)) + + oneOf(list(self._accent_map) + list(self._wide_accents)) - p.placeable ) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index c950460e07fe..ea3ba9cbf149 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -2572,7 +2572,7 @@ def mapped_r2field(name): if jointype != 'inner' and defaults is not None: # fill in the defaults enmasse - newrec_fields = list(six.iterkeys(newrec.dtype.fields)) + newrec_fields = list(newrec.dtype.fields) for k, v in six.iteritems(defaults): if k in newrec_fields: newrec[k] = v diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index 30a5224d9471..f186b46ed040 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -1236,20 +1236,16 @@ def __init__(self, s, loc, pad=0.4, borderpad=0.5, prop=None, **kwargs): if prop is None: prop = {} - propkeys = list(six.iterkeys(prop)) - badkwargs = ('ha', 'horizontalalignment', 'va', 'verticalalignment') - if set(badkwargs) & set(propkeys): + badkwargs = {'ha', 'horizontalalignment', 'va', 'verticalalignment'} + if badkwargs & set(prop): warnings.warn("Mixing horizontalalignment or verticalalignment " - "with AnchoredText is not supported.") + "with AnchoredText is not supported.") - self.txt = TextArea(s, textprops=prop, - minimumdescent=False) + self.txt = TextArea(s, textprops=prop, minimumdescent=False) fp = self.txt._text.get_fontproperties() - - super(AnchoredText, self).__init__(loc, pad=pad, borderpad=borderpad, - child=self.txt, - prop=fp, - **kwargs) + super(AnchoredText, self).__init__( + loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp, + **kwargs) class OffsetImage(OffsetBox): diff --git a/lib/matplotlib/path.py b/lib/matplotlib/path.py index 67959cc84c7a..58e984d2cc5d 100644 --- a/lib/matplotlib/path.py +++ b/lib/matplotlib/path.py @@ -203,9 +203,7 @@ def _fast_from_codes_and_verts(cls, verts, codes, internals=None): if internals: raise ValueError('Unexpected internals provided to ' '_fast_from_codes_and_verts: ' - '{0}'.format('\n *'.join(six.iterkeys( - internals - )))) + '{0}'.format('\n *'.join(internals))) return pth def _update_values(self): diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index 63b1988a5843..326812ec55b0 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -256,7 +256,7 @@ def __init__(self, ax, loc=None, bbox=None, **kwargs): if is_string_like(loc) and loc not in self.codes: warnings.warn('Unrecognized location %s. Falling back on ' 'bottom; valid locations are\n%s\t' % - (loc, '\n\t'.join(six.iterkeys(self.codes)))) + (loc, '\n\t'.join(self.codes))) loc = 'bottom' if is_string_like(loc): loc = self.codes.get(loc, 1) @@ -328,8 +328,7 @@ def _get_grid_bbox(self, renderer): Only include those in the range (0,0) to (maxRow, maxCol)""" boxes = [self._cells[pos].get_window_extent(renderer) - for pos in six.iterkeys(self._cells) - if pos[0] >= 0 and pos[1] >= 0] + for pos in self._cells if pos[0] >= 0 and pos[1] >= 0] bbox = Bbox.union(boxes) return bbox.inverse_transformed(self.get_transform()) @@ -346,9 +345,9 @@ def contains(self, mouseevent): # doesn't have to bind to each one individually. renderer = self.figure._cachedRenderer if renderer is not None: - boxes = [self._cells[pos].get_window_extent(renderer) - for pos in six.iterkeys(self._cells) - if pos[0] >= 0 and pos[1] >= 0] + boxes = [cell.get_window_extent(renderer) + for (row, col), cell in six.iteritems(self._cells) + if row >= 0 and col >= 0] bbox = Bbox.union(boxes) return bbox.contains(mouseevent.x, mouseevent.y), {} else: diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py index 00b8258db1e9..ea0b04ac8024 100644 --- a/lib/matplotlib/testing/compare.py +++ b/lib/matplotlib/testing/compare.py @@ -157,7 +157,7 @@ def comparable_formats(): on this system. """ - return ['png'] + list(six.iterkeys(converter)) + return ['png'] + list(converter) def convert(filename, cache): diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 0e0752084baf..b8274ea460de 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -624,7 +624,7 @@ def test_pandas_iterable(): def test_colormap_reversing(): """Check the generated _lut data of a colormap and corresponding reversed colormap if they are almost the same.""" - for name in six.iterkeys(cm.cmap_d): + for name in cm.cmap_d: cmap = plt.get_cmap(name) cmap_r = cmap.reversed() if not cmap_r._isinit: diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index a5f7b9e41435..a1c977825499 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -113,7 +113,7 @@ def test_RcParams_class(): # test the find_all functionality assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]').keys()) - assert ['font.family'] == list(six.iterkeys(rc.find_all('family'))) + assert ['font.family'] == list(rc.find_all('family')) def test_rcparams_update(): @@ -153,7 +153,7 @@ def test_Bug_2543(): category=UserWarning) with mpl.rc_context(): _copy = mpl.rcParams.copy() - for key in six.iterkeys(_copy): + for key in _copy: mpl.rcParams[key] = _copy[key] mpl.rcParams['text.dvipnghack'] = None with mpl.rc_context(): From 5bfd4b71d4ff4278d966cf9c495e97a4cfc7c190 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 20:13:04 -0800 Subject: [PATCH 3/9] Use ndim, size whereever appropriate. --- examples/statistics/errorbar_limits.py | 2 +- lib/matplotlib/axes/_axes.py | 4 ++-- lib/matplotlib/image.py | 3 +-- lib/matplotlib/mlab.py | 12 ++++-------- lib/matplotlib/testing/compare.py | 2 +- lib/matplotlib/tests/test_axes.py | 10 +++++----- lib/matplotlib/tri/triangulation.py | 8 +++----- lib/matplotlib/tri/triinterpolate.py | 2 +- lib/mpl_toolkits/mplot3d/proj3d.py | 9 +-------- 9 files changed, 19 insertions(+), 33 deletions(-) diff --git a/examples/statistics/errorbar_limits.py b/examples/statistics/errorbar_limits.py index a765445598fb..05d2c35be1a0 100644 --- a/examples/statistics/errorbar_limits.py +++ b/examples/statistics/errorbar_limits.py @@ -52,7 +52,7 @@ # Plot a series with lower and upper limits in both x & y # constant x-error with varying y-error xerr = 0.2 -yerr = np.zeros(x.shape) + 0.2 +yerr = np.zeros_like(x) + 0.2 yerr[[3, 6]] = 0.3 # mock up some limits by modifying previous data diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index b44e3acace53..ea8971745d82 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -5200,10 +5200,10 @@ def _pcolorargs(funcname, *args, **kw): Nx = X.shape[-1] Ny = Y.shape[0] - if len(X.shape) != 2 or X.shape[0] == 1: + if X.ndim != 2 or X.shape[0] == 1: x = X.reshape(1, Nx) X = x.repeat(Ny, axis=0) - if len(Y.shape) != 2 or Y.shape[1] == 1: + if Y.ndim != 2 or Y.shape[1] == 1: y = Y.reshape(Ny, 1) Y = y.repeat(Nx, axis=1) if X.shape != Y.shape: diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 32696d035b90..02d1df4b5869 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -848,8 +848,7 @@ def set_data(self, x, y, A): x = np.array(x, np.float32) y = np.array(y, np.float32) A = cbook.safe_masked_invalid(A, copy=True) - if len(x.shape) != 1 or len(y.shape) != 1\ - or A.shape[0:2] != (y.shape[0], x.shape[0]): + if not (x.ndim == y.ndim == 1 and A.shape[0:2] == y.shape + x.shape): raise TypeError("Axes don't match array shape") if A.ndim not in [2, 3]: raise TypeError("Can only plot 2D or 3D data") diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index ea3ba9cbf149..6311d4d7abc9 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -802,7 +802,7 @@ def _single_spectrum_helper(x, mode, Fs=None, window=None, pad_to=None, if mode != 'complex': spec = spec.real - if len(spec.shape) == 2 and spec.shape[1] == 1: + if spec.ndim == 2 and spec.shape[1] == 1: spec = spec[:, 0] return spec, freqs @@ -1013,7 +1013,7 @@ def csd(x, y, NFFT=None, Fs=None, detrend=None, window=None, sides=sides, scale_by_freq=scale_by_freq, mode='psd') - if len(Pxy.shape) == 2: + if Pxy.ndim == 2: if Pxy.shape[1] > 1: Pxy = Pxy.mean(axis=1) else: @@ -1671,16 +1671,12 @@ def project(self, x, minfrac=0.): of variance= minfrac - if ndims == 2: + if x.ndim == 2: Yreduced = Y[:, mask] else: Yreduced = Y[mask] diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py index ea0b04ac8024..10f56258183d 100644 --- a/lib/matplotlib/testing/compare.py +++ b/lib/matplotlib/testing/compare.py @@ -254,7 +254,7 @@ def calculate_rms(expectedImage, actualImage): raise ImageComparisonFailure( "image sizes do not match expected size: {0} " "actual size {1}".format(expectedImage.shape, actualImage.shape)) - num_values = np.prod(expectedImage.shape) + num_values = expectedImage.size abs_diff_image = abs(expectedImage - actualImage) histogram = np.bincount(abs_diff_image.ravel(), minlength=256) sum_of_squares = np.sum(histogram * np.arange(len(histogram)) ** 2) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index f070b320d4b4..9a1bde65281d 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2390,13 +2390,13 @@ def test_errorbar_limits(): plt.errorbar(x, y, xerr=xerr, yerr=yerr, ls=ls, color='blue') # including upper limits - uplims = np.zeros(x.shape) + uplims = np.zeros_like(x) uplims[[1, 5, 9]] = True plt.errorbar(x, y+0.5, xerr=xerr, yerr=yerr, uplims=uplims, ls=ls, color='green') # including lower limits - lolims = np.zeros(x.shape) + lolims = np.zeros_like(x) lolims[[2, 4, 8]] = True plt.errorbar(x, y+1.0, xerr=xerr, yerr=yerr, lolims=lolims, ls=ls, color='red') @@ -2407,12 +2407,12 @@ def test_errorbar_limits(): # including xlower and xupper limits xerr = 0.2 - yerr = np.zeros(x.shape) + 0.2 + yerr = np.zeros_like(x) + 0.2 yerr[[3, 6]] = 0.3 xlolims = lolims xuplims = uplims - lolims = np.zeros(x.shape) - uplims = np.zeros(x.shape) + lolims = np.zeros_like(x) + uplims = np.zeros_like(x) lolims[[6]] = True uplims[[3]] = True plt.errorbar(x, y+2.1, marker='o', ms=8, xerr=xerr, yerr=yerr, diff --git a/lib/matplotlib/tri/triangulation.py b/lib/matplotlib/tri/triangulation.py index 69c4c153e715..838f9a1ad854 100644 --- a/lib/matplotlib/tri/triangulation.py +++ b/lib/matplotlib/tri/triangulation.py @@ -41,7 +41,7 @@ class Triangulation(object): def __init__(self, x, y, triangles=None, mask=None): self.x = np.asarray(x, dtype=np.float64) self.y = np.asarray(y, dtype=np.float64) - if self.x.shape != self.y.shape or len(self.x.shape) != 1: + if self.x.shape != self.y.shape or self.x.ndim != 1: raise ValueError("x and y must be equal-length 1-D arrays") self.mask = None @@ -67,8 +67,7 @@ def __init__(self, x, y, triangles=None, mask=None): if mask is not None: self.mask = np.asarray(mask, dtype=np.bool) - if (len(self.mask.shape) != 1 or - self.mask.shape[0] != self.triangles.shape[0]): + if self.mask.shape != (self.triangles.shape[0],): raise ValueError('mask array must have same length as ' 'triangles array') @@ -202,8 +201,7 @@ def set_mask(self, mask): self.mask = None else: self.mask = np.asarray(mask, dtype=np.bool) - if (len(self.mask.shape) != 1 or - self.mask.shape[0] != self.triangles.shape[0]): + if self.mask.shape != (self.triangles.shape[0],): raise ValueError('mask array must have same length as ' 'triangles array') diff --git a/lib/matplotlib/tri/triinterpolate.py b/lib/matplotlib/tri/triinterpolate.py index 5dd75207975c..fda01095333e 100644 --- a/lib/matplotlib/tri/triinterpolate.py +++ b/lib/matplotlib/tri/triinterpolate.py @@ -166,7 +166,7 @@ def _interpolate_multikeys(self, x, y, tri_index=None, x = np.asarray(x, dtype=np.float64) y = np.asarray(y, dtype=np.float64) sh_ret = x.shape - if (x.shape != y.shape): + if x.shape != y.shape: raise ValueError("x and y shall have same shapes." " Given: {0} and {1}".format(x.shape, y.shape)) x = np.ravel(x) diff --git a/lib/mpl_toolkits/mplot3d/proj3d.py b/lib/mpl_toolkits/mplot3d/proj3d.py index 7b787ea4ac29..a3755c0bd1fd 100644 --- a/lib/mpl_toolkits/mplot3d/proj3d.py +++ b/lib/mpl_toolkits/mplot3d/proj3d.py @@ -152,14 +152,7 @@ def inv_transform(xs, ys, zs, M): return vecr[0], vecr[1], vecr[2] def vec_pad_ones(xs, ys, zs): - try: - try: - vec = np.array([xs,ys,zs,np.ones(xs.shape)]) - except (AttributeError,TypeError): - vec = np.array([xs,ys,zs,np.ones((len(xs)))]) - except TypeError: - vec = np.array([xs,ys,zs,1]) - return vec + return np.array([xs, ys, zs, np.ones_like(xs)]) def proj_transform(xs, ys, zs, M): """ From 1d4192ce0c1d326ab4e92cde0cc91a01ce5d27ce Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 20:28:46 -0800 Subject: [PATCH 4/9] Use \N{} unicode entities. --- examples/api/custom_projection_example.py | 5 +++-- examples/api/custom_scale_example.py | 3 +-- examples/pylab_examples/tex_unicode_demo.py | 2 +- lib/matplotlib/backends/backend_pdf.py | 2 +- lib/matplotlib/projections/geo.py | 5 +++-- lib/matplotlib/projections/polar.py | 9 +++------ lib/matplotlib/tests/test_image.py | 9 --------- lib/matplotlib/ticker.py | 6 +++--- tools/test_triage.py | 11 ++++------- 9 files changed, 19 insertions(+), 33 deletions(-) diff --git a/examples/api/custom_projection_example.py b/examples/api/custom_projection_example.py index 2089af37cf6c..7dc0ca2b1e41 100644 --- a/examples/api/custom_projection_example.py +++ b/examples/api/custom_projection_example.py @@ -47,7 +47,7 @@ def __call__(self, x, pos=None): if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % degrees else: - return "%0.0f\u00b0" % degrees + return "%0.0f\N{DEGREE SIGN}" % degrees RESOLUTION = 75 @@ -286,7 +286,8 @@ def format_coord(self, lon, lat): ew = 'E' else: ew = 'W' - return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(lon), ew) + return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s' + % (abs(lat), ns, abs(lon), ew)) def set_longitude_grid(self, degrees): """ diff --git a/examples/api/custom_scale_example.py b/examples/api/custom_scale_example.py index ce4889dd3fd3..12a890c53eb3 100644 --- a/examples/api/custom_scale_example.py +++ b/examples/api/custom_scale_example.py @@ -86,8 +86,7 @@ def set_default_locators_and_formatters(self, axis): """ class DegreeFormatter(Formatter): def __call__(self, x, pos=None): - # \u00b0 : degree symbol - return "%d\u00b0" % (np.degrees(x)) + return "%d\N{DEGREE SIGN}" % np.degrees(x) axis.set_major_locator(FixedLocator( np.radians(np.arange(-90, 90, 10)))) diff --git a/examples/pylab_examples/tex_unicode_demo.py b/examples/pylab_examples/tex_unicode_demo.py index d0a4f96a25c5..822f3a3cfc4f 100755 --- a/examples/pylab_examples/tex_unicode_demo.py +++ b/examples/pylab_examples/tex_unicode_demo.py @@ -18,7 +18,7 @@ plt.plot(t, s) plt.xlabel(r'\textbf{time (s)}') -plt.ylabel('\\textit{Velocity (\u00B0/sec)}', fontsize=16) +plt.ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}', fontsize=16) plt.title(r'\TeX\ is Number $\displaystyle\sum_{n=1}^\infty' r'\frac{-e^{i\pi}}{2^n}$!', fontsize=16, color='r') plt.grid(True) diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 16c5e52319b4..8f0a3a295bc1 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -1031,7 +1031,7 @@ def embedTTFType42(font, characters, descriptor): # Make the 'W' (Widths) array, CidToGidMap and ToUnicode CMap # at the same time - cid_to_gid_map = ['\u0000'] * 65536 + cid_to_gid_map = ['\0'] * 65536 widths = [] max_ccode = 0 for c in characters: diff --git a/lib/matplotlib/projections/geo.py b/lib/matplotlib/projections/geo.py index 30d616ae8757..a428b1380cb6 100644 --- a/lib/matplotlib/projections/geo.py +++ b/lib/matplotlib/projections/geo.py @@ -38,7 +38,7 @@ def __call__(self, x, pos=None): if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % degrees else: - return "%0.0f\u00b0" % degrees + return "%0.0f\N{DEGREE SIGN}" % degrees RESOLUTION = 75 @@ -183,7 +183,8 @@ def format_coord(self, lon, lat): ew = 'E' else: ew = 'W' - return '%f\u00b0%s, %f\u00b0%s' % (abs(lat), ns, abs(lon), ew) + return ('%f\N{DEGREE SIGN}%s, %f\N{DEGREE SIGN}%s' + % (abs(lat), ns, abs(lon), ew)) def set_longitude_grid(self, degrees): """ diff --git a/lib/matplotlib/projections/polar.py b/lib/matplotlib/projections/polar.py index 3cb816dc5da6..a5d2b03c34b5 100644 --- a/lib/matplotlib/projections/polar.py +++ b/lib/matplotlib/projections/polar.py @@ -172,7 +172,6 @@ class ThetaFormatter(Formatter): unit of radians into degrees and adds a degree symbol. """ def __call__(self, x, pos=None): - # \u00b0 : degree symbol if rcParams['text.usetex'] and not rcParams['text.latex.unicode']: return r"$%0.0f^\circ$" % ((x / np.pi) * 180.0) else: @@ -181,7 +180,7 @@ def __call__(self, x, pos=None): # (assuming it has a degree sign), whereas $5\circ$ # will only work correctly with one of the supported # math fonts (Computer Modern and STIX) - return "%0.0f\u00b0" % ((x / np.pi) * 180.0) + return "%0.0f\N{DEGREE SIGN}" % ((x / np.pi) * 180.0) class RadialLocator(Locator): @@ -592,10 +591,8 @@ def format_coord(self, theta, r): characters. """ theta /= math.pi - # \u03b8: lower-case theta - # \u03c0: lower-case pi - # \u00b0: degree symbol - return '\u03b8=%0.3f\u03c0 (%0.3f\u00b0), r=%0.3f' % (theta, theta * 180.0, r) + return ('\N{GREEK SMALL LETTER THETA}=%0.3f\N{GREEK SMALL LETTER PI} ' + '(%0.3f\N{DEGREE SIGN}), r=%0.3f') % (theta, theta * 180.0, r) def get_data_ratio(self): ''' diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index d87e1e3edec7..baed6294934a 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -113,15 +113,6 @@ def test_imread_pil_uint16(): assert (img.dtype == np.uint16) assert np.sum(img) == 134184960 -# def test_image_unicode_io(): -# fig = plt.figure() -# ax = fig.add_subplot(111) -# ax.plot([1,2,3]) -# fname = u"\u0a3a\u0a3a.png" -# fig.savefig(fname) -# plt.imread(fname) -# os.remove(fname) - @cleanup def test_imsave(): diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index afea9f748e05..e5da3ce02670 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -579,7 +579,7 @@ def fix_minus(self, s): if rcParams['text.usetex'] or not rcParams['axes.unicode_minus']: return s else: - return s.replace('-', '\u2212') + return s.replace('-', '\N{MINUS SIGN}') def __call__(self, x, pos=None): """ @@ -1202,7 +1202,7 @@ class EngFormatter(Formatter): -15: "f", -12: "p", -9: "n", - -6: "\u03bc", + -6: "\N{GREEK SMALL LETTER MU}", -3: "m", 0: "", 3: "k", @@ -1236,7 +1236,7 @@ def format_eng(self, num): '1.0 M' >>> format_eng("-1e-6") # for self.places = 2 - u'-1.00 \u03bc' + u'-1.00 \N{GREEK SMALL LETTER MU}' `num` may be a numeric value or a string that can be converted to a numeric value with the `decimal.Decimal` constructor. diff --git a/tools/test_triage.py b/tools/test_triage.py index a98e70e04717..f378ef371ff8 100644 --- a/tools/test_triage.py +++ b/tools/test_triage.py @@ -301,14 +301,11 @@ def display(self): Get the display string for this entry. This is the text that appears in the list widget. """ - status_map = { - 'unknown': '\u2610', - 'accept': '\u2611', - 'reject': '\u2612' - } + status_map = {'unknown': '\N{BALLOT BOX}', + 'accept': '\N{BALLOT BOX WITH CHECK}', + 'reject': '\N{BALLOT BOX WITH X}'} box = status_map[self.status] - return '{} {} [{}]'.format( - box, self.name, self.extension) + return '{} {} [{}]'.format(box, self.name, self.extension) def accept(self): """ From 39352a87b4e1094f28746409f310b5d2d681e1ed Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 2 Dec 2016 00:15:00 -0800 Subject: [PATCH 5/9] dict.keys() is nearly always useless. --- doc/sphinxext/gen_gallery.py | 2 +- doc/sphinxext/gen_rst.py | 3 +- examples/pylab_examples/fancybox_demo2.py | 6 +-- examples/statistics/bxp_demo.py | 2 +- examples/units/basic_units.py | 4 +- examples/user_interfaces/toolmanager.py | 12 ++--- lib/matplotlib/__init__.py | 7 +-- lib/matplotlib/afm.py | 5 +- lib/matplotlib/animation.py | 2 +- lib/matplotlib/axes/_base.py | 4 +- lib/matplotlib/backend_tools.py | 2 +- lib/matplotlib/backends/backend_pgf.py | 2 +- lib/matplotlib/category.py | 2 +- lib/matplotlib/cm.py | 2 +- lib/matplotlib/dates.py | 3 +- lib/matplotlib/font_manager.py | 5 +- lib/matplotlib/markers.py | 2 +- lib/matplotlib/mlab.py | 4 +- lib/matplotlib/offsetbox.py | 4 +- lib/matplotlib/patches.py | 5 +- lib/matplotlib/pyplot.py | 2 +- lib/matplotlib/style/core.py | 5 +- lib/matplotlib/table.py | 2 +- lib/matplotlib/tests/test_arrow_patches.py | 2 +- lib/matplotlib/tests/test_axes.py | 2 +- lib/matplotlib/tests/test_backend_pdf.py | 4 +- lib/matplotlib/tests/test_cbook.py | 59 ++++----------------- lib/matplotlib/tests/test_rcparams.py | 2 +- lib/matplotlib/tests/test_ticker.py | 2 +- lib/matplotlib/ticker.py | 4 +- lib/matplotlib/widgets.py | 5 +- lib/mpl_toolkits/axes_grid1/axes_divider.py | 2 +- lib/mpl_toolkits/axisartist/angle_helper.py | 4 +- lib/mpl_toolkits/gtktools.py | 3 +- lib/mpl_toolkits/mplot3d/axes3d.py | 6 +-- 35 files changed, 66 insertions(+), 116 deletions(-) diff --git a/doc/sphinxext/gen_gallery.py b/doc/sphinxext/gen_gallery.py index 520bb958d87b..812a0b4ad6ab 100644 --- a/doc/sphinxext/gen_gallery.py +++ b/doc/sphinxext/gen_gallery.py @@ -152,7 +152,7 @@ def gen_gallery(app, doctree): fh.write(content) for key in app.builder.status_iterator( - iter(thumbnails.keys()), "generating thumbnails... ", + iter(thumbnails), "generating thumbnails... ", length=len(thumbnails)): if out_of_date(key, thumbnails[key]): image.thumbnail(key, thumbnails[key], 0.3) diff --git a/doc/sphinxext/gen_rst.py b/doc/sphinxext/gen_rst.py index eff0709f1b6f..c4a07cd46695 100644 --- a/doc/sphinxext/gen_rst.py +++ b/doc/sphinxext/gen_rst.py @@ -51,8 +51,7 @@ def generate_example_rst(app): relpath = os.path.split(root)[-1] datad.setdefault(relpath, []).append((fullpath, fname, contents)) - subdirs = list(datad.keys()) - subdirs.sort() + subdirs = sorted(datad) fhindex = open(os.path.join(exampledir, 'index.rst'), 'w') fhindex.write("""\ diff --git a/examples/pylab_examples/fancybox_demo2.py b/examples/pylab_examples/fancybox_demo2.py index dc953d4866d5..3991ceebcfe8 100644 --- a/examples/pylab_examples/fancybox_demo2.py +++ b/examples/pylab_examples/fancybox_demo2.py @@ -8,11 +8,11 @@ fig1 = plt.figure(1, (4/1.5, figheight/1.5)) fontsize = 0.3 * 72 -for i, stylename in enumerate(sorted(styles.keys())): - fig1.text(0.5, (spacing * (float(len(styles)) - i) - 0.5)/figheight, stylename, +for i, stylename in enumerate(sorted(styles)): + fig1.text(0.5, (spacing * (len(styles) - i) - 0.5) / figheight, stylename, ha="center", size=fontsize, transform=fig1.transFigure, bbox=dict(boxstyle=stylename, fc="w", ec="k")) -plt.draw() + plt.show() diff --git a/examples/statistics/bxp_demo.py b/examples/statistics/bxp_demo.py index b58cbaf91ec4..bb06214f778a 100644 --- a/examples/statistics/bxp_demo.py +++ b/examples/statistics/bxp_demo.py @@ -32,7 +32,7 @@ stats[n]['med'] = np.median(data) stats[n]['mean'] *= 2 -print(stats[0].keys()) +print(list(stats[0])) fs = 10 # fontsize diff --git a/examples/units/basic_units.py b/examples/units/basic_units.py index cea1c2626b5e..6f26e1fc0d5c 100644 --- a/examples/units/basic_units.py +++ b/examples/units/basic_units.py @@ -17,9 +17,9 @@ def __get__(self, obj, objtype=None): return self.proxy_type(self.fn_name, obj) -class TaggedValueMeta (type): +class TaggedValueMeta(type): def __init__(cls, name, bases, dict): - for fn_name in cls._proxies.keys(): + for fn_name in cls._proxies: try: dummy = getattr(cls, fn_name) except AttributeError: diff --git a/examples/user_interfaces/toolmanager.py b/examples/user_interfaces/toolmanager.py index 64a5a14c2d95..6bda3242ed54 100644 --- a/examples/user_interfaces/toolmanager.py +++ b/examples/user_interfaces/toolmanager.py @@ -24,18 +24,16 @@ class ListTools(ToolBase): def trigger(self, *args, **kwargs): print('_' * 80) - print("{0:12} {1:45} {2}".format('Name (id)', - 'Tool description', - 'Keymap')) + print("{0:12} {1:45} {2}".format( + 'Name (id)', 'Tool description', 'Keymap')) print('-' * 80) tools = self.toolmanager.tools - for name in sorted(tools.keys()): + for name in sorted(tools): if not tools[name].description: continue keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name))) - print("{0:12} {1:45} {2}".format(name, - tools[name].description, - keys)) + print("{0:12} {1:45} {2}".format( + name, tools[name].description, keys)) print('_' * 80) print("Active Toggle tools") print("{0:12} {1:45}".format("Group", "Active")) diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 1bdab1dc8069..89e7e2381164 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -916,8 +916,9 @@ def __setitem__(self, key, val): raise ValueError("Key %s: %s" % (key, str(ve))) dict.__setitem__(self, key, cval) except KeyError: - raise KeyError('%s is not a valid rc parameter.\ -See rcParams.keys() for a list of valid parameters.' % (key,)) + raise KeyError( + '%s is not a valid rc parameter. See rcParams.keys() for a ' + 'list of valid parameters.' % (key,)) def __getitem__(self, key): inverse_alt = None @@ -974,7 +975,7 @@ def values(self): """ Return values in order of sorted keys. """ - return [self[k] for k in self.keys()] + return [self[k] for k in self] def find_all(self, pattern): """ diff --git a/lib/matplotlib/afm.py b/lib/matplotlib/afm.py index ec7867799e44..f784aa55cd03 100644 --- a/lib/matplotlib/afm.py +++ b/lib/matplotlib/afm.py @@ -199,10 +199,9 @@ def _parse_char_metrics(fh): if line.startswith('EndCharMetrics'): return ascii_d, name_d # Split the metric line into a dictonary, keyed by metric identifiers - vals = filter(lambda s: len(s) > 0, line.split(';')) - vals = dict(map(lambda s: tuple(s.strip().split(' ', 1)), vals)) + vals = dict(s.strip().split(' ', 1) for s in line.split(';') if s) # There may be other metrics present, but only these are needed - if any([id not in vals.keys() for id in ('C', 'WX', 'N', 'B')]): + if not {'C', 'WX', 'N', 'B'}.issubset(vals): raise RuntimeError('Bad char metrics line: %s' % line) num = _to_int(vals['C']) wx = _to_float(vals['WX']) diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index fee64a1e1f79..ec95cbb4f501 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -108,7 +108,7 @@ def reset_available_writers(self): def list(self): ''' Get a list of available MovieWriters.''' self.ensure_not_dirty() - return list(self.avail.keys()) + return list(self.avail) def is_available(self, name): '''Check if given writer is available by name. diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 7bb675a497b5..2b23d9198212 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -2942,7 +2942,7 @@ def set_xscale(self, value, **kwargs): """ # If the scale is being set to log, clip nonposx to prevent headaches # around zero - if value.lower() == 'log' and 'nonposx' not in kwargs.keys(): + if value.lower() == 'log' and 'nonposx' not in kwargs: kwargs['nonposx'] = 'clip' g = self.get_shared_x_axes() @@ -3222,7 +3222,7 @@ def set_yscale(self, value, **kwargs): """ # If the scale is being set to log, clip nonposy to prevent headaches # around zero - if value.lower() == 'log' and 'nonposy' not in kwargs.keys(): + if value.lower() == 'log' and 'nonposy' not in kwargs: kwargs['nonposy'] = 'clip' g = self.get_shared_y_axes() diff --git a/lib/matplotlib/backend_tools.py b/lib/matplotlib/backend_tools.py index a194523b7d50..66e43394e34f 100644 --- a/lib/matplotlib/backend_tools.py +++ b/lib/matplotlib/backend_tools.py @@ -618,7 +618,7 @@ def update_view(self): cur_view = home_views[a] a._set_view(cur_view) - if set(all_axes).issubset(pos.keys()): + if set(all_axes).issubset(pos): for a in all_axes: # Restore both the original and modified positions a.set_position(pos[a][0], 'original') diff --git a/lib/matplotlib/backends/backend_pgf.py b/lib/matplotlib/backends/backend_pgf.py index 5d9a905de5d7..eb181986252c 100644 --- a/lib/matplotlib/backends/backend_pgf.py +++ b/lib/matplotlib/backends/backend_pgf.py @@ -424,7 +424,7 @@ def __init__(self, figure, fh, dummy=False): if dummy: # dummy==True deactivate all methods nop = lambda *args, **kwargs: None - for m in RendererPgf.__dict__.keys(): + for m in RendererPgf.__dict__: if m.startswith("draw_"): self.__dict__[m] = nop else: diff --git a/lib/matplotlib/category.py b/lib/matplotlib/category.py index 5a425f890e2d..a1ca001fe587 100644 --- a/lib/matplotlib/category.py +++ b/lib/matplotlib/category.py @@ -86,7 +86,7 @@ def _set_seq_locs(self, data, value): new_s = [d for d in np.unique(strdata) if d not in self.seq] for ns in new_s: self.seq.append(ns) - if ns in UnitData.spdict.keys(): + if ns in UnitData.spdict: self.locs.append(UnitData.spdict[ns]) else: self.locs.append(value) diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 7c1fac5d5d20..e26d22c1f7ef 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -170,7 +170,7 @@ def get_cmap(name=None, lut=None): else: raise ValueError( "Colormap %s is not recognized. Possible values are: %s" - % (name, ', '.join(sorted(cmap_d.keys())))) + % (name, ', '.join(sorted(cmap_d)))) class ScalarMappable(object): diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index 3a968b0bd268..d9b56d759366 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -958,8 +958,7 @@ def __init__(self, tz=None, minticks=5, maxticks=None, # Assume we were given an integer. Use this as the maximum # number of ticks for every frequency and create a # dictionary for this - self.maxticks = dict(zip(self._freqs, - [maxticks] * len(self._freqs))) + self.maxticks = dict.fromkeys(self._freqs, maxticks) self.interval_multiples = interval_multiples self.intervald = { YEARLY: [1, 2, 4, 5, 10, 20, 40, 50, 100, 200, 400, 500, diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index edbb055918ea..284f9109aedc 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -891,11 +891,10 @@ def set_size(self, size): scale = font_scalings[size] except KeyError: raise ValueError( - "Size is invalid. Valid font size are " + ", ".join( - str(i) for i in font_scalings.keys())) + "Size is invalid. Valid font size are " + + ", ".join(map(str, font_scalings))) else: size = scale * FontManager.get_default_size() - self._size = size def set_file(self, file): diff --git a/lib/matplotlib/markers.py b/lib/matplotlib/markers.py index 773e0b7fd1e0..364dc1dac7f0 100644 --- a/lib/matplotlib/markers.py +++ b/lib/matplotlib/markers.py @@ -99,7 +99,7 @@ # special-purpose marker identifiers: (TICKLEFT, TICKRIGHT, TICKUP, TICKDOWN, CARETLEFT, CARETRIGHT, CARETUP, CARETDOWN, - CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = list(xrange(12)) + CARETLEFTBASE, CARETRIGHTBASE, CARETUPBASE, CARETDOWNBASE) = xrange(12) _empty_path = Path(np.empty((0, 2))) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 6311d4d7abc9..6de2d740417d 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -2487,8 +2487,8 @@ def makekey(row): r1d = {makekey(row): i for i, row in enumerate(r1)} r2d = {makekey(row): i for i, row in enumerate(r2)} - r1keys = set(r1d.keys()) - r2keys = set(r2d.keys()) + r1keys = set(r1d) + r2keys = set(r2d) common_keys = r1keys & r2keys diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index f186b46ed040..a1376c645737 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -67,7 +67,7 @@ def _get_packed_offsets(wd_list, total, sep, mode="fixed"): *mode* : packing mode. 'fixed', 'expand', or 'equal'. """ - w_list, d_list = list(zip(*wd_list)) + w_list, d_list = zip(*wd_list) # d_list is currently not used. if mode == "fixed": @@ -1183,7 +1183,7 @@ def _get_anchored_bbox(self, loc, bbox, parentbbox, borderpad): """ assert loc in range(1, 11) # called only internally - BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11)) + BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = xrange(11) anchor_coefs = {UR: "NE", UL: "NW", diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 8e85f89e3f26..dad558fd1bc1 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1840,10 +1840,7 @@ def _simpleprint_styles(_styles): (stylename : styleclass), return a string rep of the list of keys. Used to update the documentation. """ - styles = "[ \'" - styles += "\' | \'".join(str(i) for i in sorted(_styles.keys())) - styles += "\' ]" - return styles + return "[{}]".format("|".join(map(" '{}' ".format, sorted(_styles)))) class _Style(object): diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index f837db3bcdfb..161e10444345 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -2096,7 +2096,7 @@ def colormaps(): """ - return sorted(cm.cmap_d.keys()) + return sorted(cm.cmap_d) def _setup_pyplot_info_docstrings(): diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index 098f45d5b426..3514dd93026b 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -218,7 +218,6 @@ def update_nested_dict(main_dict, new_dict): def reload_library(): """Reload style library.""" - global library, available - library = update_user_library(_base_library) - available[:] = library.keys() + global library + available[:] = library = update_user_library(_base_library) reload_library() diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index 326812ec55b0..ebd4d760b06a 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -520,7 +520,7 @@ def _update_positions(self, renderer): else: # Position using loc (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, - TR, TL, BL, BR, R, L, T, B) = list(xrange(len(self.codes))) + TR, TL, BL, BR, R, L, T, B) = xrange(len(self.codes)) # defaults for center ox = (0.5 - w / 2) - l oy = (0.5 - h / 2) - b diff --git a/lib/matplotlib/tests/test_arrow_patches.py b/lib/matplotlib/tests/test_arrow_patches.py index 466a53b87f82..23ed427084d9 100644 --- a/lib/matplotlib/tests/test_arrow_patches.py +++ b/lib/matplotlib/tests/test_arrow_patches.py @@ -44,7 +44,7 @@ def test_boxarrow(): fontsize = 0.3 * 72 - for i, stylename in enumerate(sorted(styles.keys())): + for i, stylename in enumerate(sorted(styles)): fig1.text(0.5, ((n - i) * spacing - 0.5)/figheight, stylename, ha="center", size=fontsize, diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 9a1bde65281d..a590b54818d7 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -2793,7 +2793,7 @@ def test_empty_eventplot(): def test_marker_styles(): fig = plt.figure() ax = fig.add_subplot(111) - for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers.keys(), + for y, marker in enumerate(sorted(matplotlib.markers.MarkerStyle.markers, key=lambda x: str(type(x))+str(x))): ax.plot((y % 2)*5 + np.arange(10)*10, np.ones(10)*10*y, linestyle='', marker=marker, markersize=10+y/5, label=marker) diff --git a/lib/matplotlib/tests/test_backend_pdf.py b/lib/matplotlib/tests/test_backend_pdf.py index ac36c50f1662..70e2ed73fe5f 100644 --- a/lib/matplotlib/tests/test_backend_pdf.py +++ b/lib/matplotlib/tests/test_backend_pdf.py @@ -124,11 +124,11 @@ def test_composite_image(): plt.rcParams['image.composite_image'] = True with PdfPages(io.BytesIO()) as pdf: fig.savefig(pdf, format="pdf") - assert len(pdf._file._images.keys()) == 1 + assert len(pdf._file._images) == 1 plt.rcParams['image.composite_image'] = False with PdfPages(io.BytesIO()) as pdf: fig.savefig(pdf, format="pdf") - assert len(pdf._file._images.keys()) == 2 + assert len(pdf._file._images) == 2 @cleanup diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 5ada77ae86cc..47ff048d349a 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -173,73 +173,36 @@ def test_form_each_dict(self): def test_form_dict_keys(self): for res in self.std_results: - keys = sorted(list(res.keys())) - for key in keys: - assert key in self.known_keys + assert set(res) <= set(self.known_keys) def test_results_baseline(self): res = self.std_results[0] - for key in list(self.known_nonbootstrapped_res.keys()): - if key != 'fliers': - assert_statement = assert_approx_equal - else: - assert_statement = assert_array_almost_equal - - assert_statement( - res[key], - self.known_nonbootstrapped_res[key] - ) + for key, value in self.known_nonbootstrapped_res.items(): + assert_array_almost_equal(res[key], value) def test_results_bootstrapped(self): results = cbook.boxplot_stats(self.data, bootstrap=10000) res = results[0] - for key in list(self.known_bootstrapped_ci.keys()): - assert_approx_equal( - res[key], - self.known_bootstrapped_ci[key] - ) + for key, value in self.known_bootstrapped_ci.items(): + assert_approx_equal(res[key], value) def test_results_whiskers_float(self): results = cbook.boxplot_stats(self.data, whis=3) res = results[0] - for key in list(self.known_whis3_res.keys()): - if key != 'fliers': - assert_statement = assert_approx_equal - else: - assert_statement = assert_array_almost_equal - - assert_statement( - res[key], - self.known_whis3_res[key] - ) + for key, value in self.known_whis3_res.items(): + assert_array_almost_equal(res[key], value) def test_results_whiskers_range(self): results = cbook.boxplot_stats(self.data, whis='range') res = results[0] - for key in list(self.known_res_range.keys()): - if key != 'fliers': - assert_statement = assert_approx_equal - else: - assert_statement = assert_array_almost_equal - - assert_statement( - res[key], - self.known_res_range[key] - ) + for key, value in self.known_res_range.items(): + assert_array_almost_equal(res[key], value) def test_results_whiskers_percentiles(self): results = cbook.boxplot_stats(self.data, whis=[5, 95]) res = results[0] - for key in list(self.known_res_percentiles.keys()): - if key != 'fliers': - assert_statement = assert_approx_equal - else: - assert_statement = assert_array_almost_equal - - assert_statement( - res[key], - self.known_res_percentiles[key] - ) + for key, value in self.known_res_percentiles.items(): + assert_array_almost_equal(res[key], value) def test_results_withlabels(self): labels = ['Test1', 2, 'ardvark', 4] diff --git a/lib/matplotlib/tests/test_rcparams.py b/lib/matplotlib/tests/test_rcparams.py index a1c977825499..aff954950e40 100644 --- a/lib/matplotlib/tests/test_rcparams.py +++ b/lib/matplotlib/tests/test_rcparams.py @@ -112,7 +112,7 @@ def test_RcParams_class(): assert_str_equal(expected_str, str(rc)) # test the find_all functionality - assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]').keys()) + assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]')) assert ['font.family'] == list(rc.find_all('family')) diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index e390237d543c..75cad9f27730 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -338,7 +338,7 @@ def test_LogFormatterSciNotation(): ) } - for base in test_cases.keys(): + for base in test_cases: formatter = mticker.LogFormatterSciNotation(base=base) formatter.sublabel = {1, 2, 5, 1.2} for value, expected in test_cases[base]: diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index e5da3ce02670..2278c33eb3c8 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -1254,8 +1254,8 @@ def format_eng(self, num): else: pow10 = decimal.Decimal(0) - pow10 = pow10.min(max(self.ENG_PREFIXES.keys())) - pow10 = pow10.max(min(self.ENG_PREFIXES.keys())) + pow10 = pow10.min(max(self.ENG_PREFIXES)) + pow10 = pow10.max(min(self.ENG_PREFIXES)) prefix = self.ENG_PREFIXES[int(pow10)] diff --git a/lib/matplotlib/widgets.py b/lib/matplotlib/widgets.py index ea6862f35248..82633f78f6b6 100644 --- a/lib/matplotlib/widgets.py +++ b/lib/matplotlib/widgets.py @@ -683,10 +683,7 @@ def __init__(self, ax, label, initial='', self.DIST_FROM_LEFT = .05 - self.params_to_disable = [] - for key in rcParams.keys(): - if u'keymap' in key: - self.params_to_disable += [key] + self.params_to_disable = [key for key in rcParams if u'keymap' in key] self.text = initial self.label = ax.text(-label_pad, 0.5, label, diff --git a/lib/mpl_toolkits/axes_grid1/axes_divider.py b/lib/mpl_toolkits/axes_grid1/axes_divider.py index 35743c474dc4..bda5bba91dc4 100644 --- a/lib/mpl_toolkits/axes_grid1/axes_divider.py +++ b/lib/mpl_toolkits/axes_grid1/axes_divider.py @@ -148,7 +148,7 @@ def set_anchor(self, anchor): self._anchor = anchor else: raise ValueError('argument must be among %s' % - ', '.join(mtransforms.BBox.coefs.keys())) + ', '.join(mtransforms.BBox.coefs)) def get_anchor(self): "return the anchor" diff --git a/lib/mpl_toolkits/axisartist/angle_helper.py b/lib/mpl_toolkits/axisartist/angle_helper.py index 5d921b0ba553..d7c6d505b737 100644 --- a/lib/mpl_toolkits/axisartist/angle_helper.py +++ b/lib/mpl_toolkits/axisartist/angle_helper.py @@ -186,8 +186,8 @@ def set_params(self, **kwargs): self.den = int(kwargs.pop("nbins")) if kwargs: - raise ValueError("Following keys are not processed: %s" % \ - ", ".join([str(k) for k in kwargs.keys()])) + raise ValueError("Following keys are not processed: %s" + % ", ".join(kwargs)) class LocatorHMS(LocatorBase): diff --git a/lib/mpl_toolkits/gtktools.py b/lib/mpl_toolkits/gtktools.py index 4067dfcdf4f2..9b5423b19f08 100644 --- a/lib/mpl_toolkits/gtktools.py +++ b/lib/mpl_toolkits/gtktools.py @@ -479,8 +479,7 @@ def __init__(self, recliststore, constant=None): gtk.TreeView.__init__(self, recliststore) - combostrings = set(recliststore.stringd.keys()) - + combostrings = set(recliststore.stringd) if constant is None: constant = [] diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 00aa7741e460..aaa705113253 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -589,7 +589,7 @@ def set_xlim3d(self, left=None, right=None, emit=True, auto=False, **kw): if 'xmax' in kw: right = kw.pop('xmax') if kw: - raise ValueError("unrecognized kwargs: %s" % kw.keys()) + raise ValueError("unrecognized kwargs: %s" % list(kw)) if right is None and cbook.iterable(left): left, right = left @@ -644,7 +644,7 @@ def set_ylim3d(self, bottom=None, top=None, emit=True, auto=False, **kw): if 'ymax' in kw: top = kw.pop('ymax') if kw: - raise ValueError("unrecognized kwargs: %s" % kw.keys()) + raise ValueError("unrecognized kwargs: %s" % list(kw)) if top is None and cbook.iterable(bottom): bottom, top = bottom @@ -698,7 +698,7 @@ def set_zlim3d(self, bottom=None, top=None, emit=True, auto=False, **kw): if 'zmax' in kw: top = kw.pop('zmax') if kw: - raise ValueError("unrecognized kwargs: %s" % kw.keys()) + raise ValueError("unrecognized kwargs: %s" % list(kw)) if top is None and cbook.iterable(bottom): bottom, top = bottom From 338f6dadfd2afa6d7f28c186bac302ac05111758 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 2 Dec 2016 00:35:04 -0800 Subject: [PATCH 6/9] safezip is (mostly) overrated. --- lib/matplotlib/axes/_axes.py | 14 ++++++-------- lib/matplotlib/legend.py | 34 ++++++++++------------------------ 2 files changed, 16 insertions(+), 32 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index ea8971745d82..e89d1d8dd3dc 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2571,11 +2571,11 @@ def pie(self, x, explode=None, labels=None, colors=None, labels. """ - x = np.asarray(x).astype(np.float32) + x = np.array(x, np.float32) - sx = float(x.sum()) + sx = x.sum() if sx > 1: - x = np.divide(x, sx) + x /= sx if labels is None: labels = [''] * len(x) @@ -2605,20 +2605,18 @@ def get_next_color(): # set default values in wedge_prop if wedgeprops is None: wedgeprops = {} - if 'clip_on' not in wedgeprops: - wedgeprops['clip_on'] = False + wedgeprops.setdefault('clip_on', False) if textprops is None: textprops = {} - if 'clip_on' not in textprops: - textprops['clip_on'] = False + textprops.setdefault('clip_on', False) texts = [] slices = [] autotexts = [] i = 0 - for frac, label, expl in cbook.safezip(x, labels, explode): + for frac, label, expl in zip(x, labels, explode): x, y = center theta2 = (theta1 + frac) if counterclock else (theta1 - frac) thetam = 2 * math.pi * 0.5 * (theta1 + theta2) diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index b940a6b0c5ea..e037ff54e57c 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -33,8 +33,7 @@ from matplotlib import rcParams from matplotlib.artist import Artist, allow_rasterization -from matplotlib.cbook import (is_string_like, iterable, silent_list, safezip, - is_hashable) +from matplotlib.cbook import is_string_like, iterable, silent_list, is_hashable from matplotlib.font_manager import FontProperties from matplotlib.lines import Line2D from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch @@ -653,29 +652,23 @@ def _init_legend_box(self, handles, labels, markerfirst=True): handle_list.append(handler.legend_artist(self, orig_handle, fontsize, handlebox)) - if len(handleboxes) > 0: - + if handleboxes: # We calculate number of rows in each column. The first # (num_largecol) columns will have (nrows+1) rows, and remaining # (num_smallcol) columns will have (nrows) rows. ncol = min(self._ncol, len(handleboxes)) nrows, num_largecol = divmod(len(handleboxes), ncol) num_smallcol = ncol - num_largecol - # starting index of each column and number of rows in it. - largecol = safezip(list(xrange(0, - num_largecol * (nrows + 1), - (nrows + 1))), - [nrows + 1] * num_largecol) - smallcol = safezip(list(xrange(num_largecol * (nrows + 1), - len(handleboxes), nrows)), - [nrows] * num_smallcol) + rows_per_col = [nrows + 1] * num_largecol + [nrows] * num_smallcol + start_idxs = np.concatenate([[0], np.cumsum(rows_per_col)[:-1]]) + cols = zip(start_idxs, rows_per_col) else: - largecol, smallcol = [], [] + cols = [] - handle_label = safezip(handleboxes, labelboxes) + handle_label = list(zip(handleboxes, labelboxes)) columnbox = [] - for i0, di in largecol + smallcol: + for i0, di in cols: # pack handleBox and labelBox into itemBox itemBoxes = [HPacker(pad=0, sep=self.handletextpad * fontsize, @@ -689,20 +682,13 @@ def _init_legend_box(self, handles, labels, markerfirst=True): itemBoxes[-1].get_children()[0].set_minimumdescent(False) # pack columnBox - if markerfirst: - alignment = "baseline" - else: - alignment = "right" + alignment = "baseline" if markerfirst else "right" columnbox.append(VPacker(pad=0, sep=self.labelspacing * fontsize, align=alignment, children=itemBoxes)) - if self._mode == "expand": - mode = "expand" - else: - mode = "fixed" - + mode = "expand" if self._mode == "expand" else "fixed" sep = self.columnspacing * fontsize self._legend_handle_box = HPacker(pad=0, sep=sep, align="baseline", From 43f2f7c46bc940716a8f25ae64d64d44d673a996 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 2 Dec 2016 00:46:21 -0800 Subject: [PATCH 7/9] alltrue and sometrue are known as all and any. --- lib/matplotlib/backends/backend_ps.py | 16 +--------------- lib/matplotlib/colors.py | 4 ++-- lib/matplotlib/figure.py | 3 +-- lib/mpl_toolkits/mplot3d/proj3d.py | 6 +++--- 4 files changed, 7 insertions(+), 22 deletions(-) diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index e0c823b9b271..1072a37f92a2 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -170,21 +170,7 @@ def quote_ps_string(s): return s.decode('ascii') -def seq_allequal(seq1, seq2): - """ - seq1 and seq2 are either None or sequences or arrays - Return True if both are None or both are seqs with identical - elements - """ - if seq1 is None: - return seq2 is None - - if seq2 is None: - return False - #ok, neither are None:, assuming iterable - - if len(seq1) != len(seq2): return False - return np.alltrue(np.equal(seq1, seq2)) +seq_allequal = np.array_equal class RendererPS(RendererBase): diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 9acd52a658e5..2b5115e4fc80 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -561,8 +561,8 @@ def _init(self): def is_gray(self): if not self._isinit: self._init() - return (np.alltrue(self._lut[:, 0] == self._lut[:, 1]) and - np.alltrue(self._lut[:, 0] == self._lut[:, 2])) + return (np.all(self._lut[:, 0] == self._lut[:, 1]) and + np.all(self._lut[:, 0] == self._lut[:, 2])) def _resample(self, lutsize): """ diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 9745a4ae2510..dbc1f4a87a22 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -457,8 +457,7 @@ def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right'): *ha* The horizontal alignment of the xticklabels """ - allsubplots = np.alltrue([hasattr(ax, 'is_last_row') for ax - in self.axes]) + allsubplots = all(hasattr(ax, 'is_last_row') for ax in self.axes) if len(self.axes) == 1: for label in self.axes[0].get_xticklabels(): label.set_ha(ha) diff --git a/lib/mpl_toolkits/mplot3d/proj3d.py b/lib/mpl_toolkits/mplot3d/proj3d.py index a3755c0bd1fd..55162f58e70b 100644 --- a/lib/mpl_toolkits/mplot3d/proj3d.py +++ b/lib/mpl_toolkits/mplot3d/proj3d.py @@ -136,9 +136,9 @@ def proj_transform_vec_clip(vec, M): w = vecw[3] # clip here.. txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w - tis = (vecw[0] >= 0) * (vecw[0] <= 1) * (vecw[1] >= 0) * (vecw[1] <= 1) - if np.sometrue(tis): - tis = vecw[1] < 1 + tis = (vecw[0] >= 0) & (vecw[0] <= 1) & (vecw[1] >= 0) & (vecw[1] <= 1) + if np.any(tis): + tis = vecw[1] < 1 return txs, tys, tzs, tis def inv_transform(xs, ys, zs, M): From 04062b64027f9b41dd82bdece94d581c0cbe27a7 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 2 Dec 2016 21:56:59 -0800 Subject: [PATCH 8/9] Cleanup while 1: ... and file iteration. --- examples/misc/multiprocess.py | 2 +- lib/matplotlib/afm.py | 37 ++++------- lib/matplotlib/axes/_base.py | 24 +++----- lib/matplotlib/backends/backend_ps.py | 89 ++++++++++++--------------- lib/matplotlib/backends/tkagg.py | 2 +- lib/matplotlib/bezier.py | 15 ++--- lib/matplotlib/dates.py | 2 +- lib/matplotlib/mlab.py | 2 +- 8 files changed, 69 insertions(+), 104 deletions(-) diff --git a/examples/misc/multiprocess.py b/examples/misc/multiprocess.py index 880675779456..a32a0f02fdf3 100644 --- a/examples/misc/multiprocess.py +++ b/examples/misc/multiprocess.py @@ -28,7 +28,7 @@ def terminate(self): def poll_draw(self): def call_back(): - while 1: + while True: if not self.pipe.poll(): break diff --git a/lib/matplotlib/afm.py b/lib/matplotlib/afm.py index f784aa55cd03..7d0b00a576f3 100644 --- a/lib/matplotlib/afm.py +++ b/lib/matplotlib/afm.py @@ -91,7 +91,7 @@ def _sanity_check(fh): # do something else with the file. pos = fh.tell() try: - line = fh.readline() + line = next(fh) finally: fh.seek(pos, 0) @@ -148,10 +148,7 @@ def _parse_header(fh): } d = {} - while 1: - line = fh.readline() - if not line: - break + for line in fh: line = line.rstrip() if line.startswith(b'Comment'): continue @@ -191,10 +188,7 @@ def _parse_char_metrics(fh): ascii_d = {} name_d = {} - while 1: - line = fh.readline() - if not line: - break + for line in fh: line = line.rstrip().decode('ascii') # Convert from byte-literal if line.startswith('EndCharMetrics'): return ascii_d, name_d @@ -231,20 +225,17 @@ def _parse_kern_pairs(fh): """ - line = fh.readline() + line = next(fh) if not line.startswith(b'StartKernPairs'): raise RuntimeError('Bad start of kern pairs data: %s' % line) d = {} - while 1: - line = fh.readline() - if not line: - break + for line in fh: line = line.rstrip() - if len(line) == 0: + if not line: continue if line.startswith(b'EndKernPairs'): - fh.readline() # EndKernData + next(fh) # EndKernData return d vals = line.split() if len(vals) != 4 or vals[0] != b'KPX': @@ -269,12 +260,9 @@ def _parse_composites(fh): """ d = {} - while 1: - line = fh.readline() - if not line: - break + for line in fh: line = line.rstrip() - if len(line) == 0: + if not line: continue if line.startswith(b'EndComposites'): return d @@ -306,12 +294,9 @@ def _parse_optional(fh): } d = {b'StartKernData': {}, b'StartComposites': {}} - while 1: - line = fh.readline() - if not line: - break + for line in fh: line = line.rstrip() - if len(line) == 0: + if not line: continue key = line.split()[0] diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 2b23d9198212..905a9bdd86aa 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -396,25 +396,15 @@ def _plot_args(self, tup, kwargs): return ret def _grab_next_args(self, *args, **kwargs): - - remaining = args - while 1: - - if len(remaining) == 0: - return - if len(remaining) <= 3: - for seg in self._plot_args(remaining, kwargs): - yield seg + while True: + if not args: return - - if is_string_like(remaining[2]): - isplit = 3 - else: - isplit = 2 - - for seg in self._plot_args(remaining[:isplit], kwargs): + this, args = args[:2], args[2:] + if args and is_string_like(args[0]): + this += args[0], + args = args[1:] + for seg in self._plot_args(this, kwargs): yield seg - remaining = remaining[isplit:] class _AxesBase(martist.Artist): diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index 1072a37f92a2..e798e149179b 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -1654,55 +1654,48 @@ def pstoeps(tmpfile, bbox=None, rotated=False): bbox_info, rotate = None, None epsfile = tmpfile + '.eps' - with io.open(epsfile, 'wb') as epsh: + with io.open(epsfile, 'wb') as epsh, io.open(tmpfile, 'rb') as tmph: write = epsh.write - with io.open(tmpfile, 'rb') as tmph: - line = tmph.readline() - # Modify the header: - while line: - if line.startswith(b'%!PS'): - write(b"%!PS-Adobe-3.0 EPSF-3.0\n") - if bbox: - write(bbox_info.encode('ascii') + b'\n') - elif line.startswith(b'%%EndComments'): - write(line) - write(b'%%BeginProlog\n') - write(b'save\n') - write(b'countdictstack\n') - write(b'mark\n') - write(b'newpath\n') - write(b'/showpage {} def\n') - write(b'/setpagedevice {pop} def\n') - write(b'%%EndProlog\n') - write(b'%%Page 1 1\n') - if rotate: - write(rotate.encode('ascii') + b'\n') - break - elif bbox and (line.startswith(b'%%Bound') \ - or line.startswith(b'%%HiResBound') \ - or line.startswith(b'%%DocumentMedia') \ - or line.startswith(b'%%Pages')): - pass - else: - write(line) - line = tmph.readline() - # Now rewrite the rest of the file, and modify the trailer. - # This is done in a second loop such that the header of the embedded - # eps file is not modified. - line = tmph.readline() - while line: - if line.startswith(b'%%EOF'): - write(b'cleartomark\n') - write(b'countdictstack\n') - write(b'exch sub { end } repeat\n') - write(b'restore\n') - write(b'showpage\n') - write(b'%%EOF\n') - elif line.startswith(b'%%PageBoundingBox'): - pass - else: - write(line) - line = tmph.readline() + # Modify the header: + for line in tmph: + if line.startswith(b'%!PS'): + write(b"%!PS-Adobe-3.0 EPSF-3.0\n") + if bbox: + write(bbox_info.encode('ascii') + b'\n') + elif line.startswith(b'%%EndComments'): + write(line) + write(b'%%BeginProlog\n' + b'save\n' + b'countdictstack\n' + b'mark\n' + b'newpath\n' + b'/showpage {} def\n' + b'/setpagedevice {pop} def\n' + b'%%EndProlog\n' + b'%%Page 1 1\n') + if rotate: + write(rotate.encode('ascii') + b'\n') + break + elif bbox and line.startswith((b'%%Bound', b'%%HiResBound', + b'%%DocumentMedia', b'%%Pages')): + pass + else: + write(line) + # Now rewrite the rest of the file, and modify the trailer. + # This is done in a second loop such that the header of the embedded + # eps file is not modified. + for line in tmph: + if line.startswith(b'%%EOF'): + write(b'cleartomark\n' + b'countdictstack\n' + b'exch sub { end } repeat\n' + b'restore\n' + b'showpage\n' + b'%%EOF\n') + elif line.startswith(b'%%PageBoundingBox'): + pass + else: + write(line) os.remove(tmpfile) shutil.move(epsfile, tmpfile) diff --git a/lib/matplotlib/backends/tkagg.py b/lib/matplotlib/backends/tkagg.py index 81fe9265a351..979bc3cc24fa 100644 --- a/lib/matplotlib/backends/tkagg.py +++ b/lib/matplotlib/backends/tkagg.py @@ -40,4 +40,4 @@ def test(aggimage): blit(p, aggimage) c.create_image(aggimage.width,aggimage.height,image=p) blit(p, aggimage) - while 1: r.update_idletasks() + while True: r.update_idletasks() diff --git a/lib/matplotlib/bezier.py b/lib/matplotlib/bezier.py index baace75fa6c1..9e21d828da6b 100644 --- a/lib/matplotlib/bezier.py +++ b/lib/matplotlib/bezier.py @@ -113,7 +113,7 @@ def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, - bezier_point_at_t : a function which returns x, y coordinates at *t* - - inside_closedpath : return True if the point is insed the path + - inside_closedpath : return True if the point is inside the path """ # inside_closedpath : function @@ -124,17 +124,14 @@ def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, start_inside = inside_closedpath(start) end_inside = inside_closedpath(end) - if start_inside == end_inside: - if start != end: - raise NonIntersectingPathException( - "the segment does not seem to intersect with the path" - ) + if start_inside == end_inside and start != end: + raise NonIntersectingPathException( + "Both points are on the same side of the closed path") - while 1: + while True: # return if the distance is smaller than the tolerence - if (start[0] - end[0]) ** 2 + \ - (start[1] - end[1]) ** 2 < tolerence ** 2: + if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerence: return t0, t1 # calculate the middle point diff --git a/lib/matplotlib/dates.py b/lib/matplotlib/dates.py index d9b56d759366..7783b783046b 100644 --- a/lib/matplotlib/dates.py +++ b/lib/matplotlib/dates.py @@ -1147,7 +1147,7 @@ def tick_values(self, vmin, vmax): ymax = self.base.ge(vmax.year) ticks = [vmin.replace(year=ymin, **self.replaced)] - while 1: + while True: dt = ticks[-1] if dt.year >= ymax: return date2num(ticks) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 6de2d740417d..0deb5b3545f7 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -2898,7 +2898,7 @@ def get_converters(reader, comments): process_skiprows(reader) if needheader: - while 1: + while True: # skip past any comments and consume one line of column header row = next(reader) if (len(row) and comments is not None and From 14b47baf5c2835bb139ddec794c96044a803ac50 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 4 Dec 2016 12:32:59 -0800 Subject: [PATCH 9/9] More cleanups following PR comments. --- doc/api/api_changes/code_removal.rst | 6 ++++++ examples/misc/multiprocess.py | 8 +------ lib/matplotlib/__init__.py | 29 +++++++------------------- lib/matplotlib/axes/_base.py | 14 ++++++------- lib/matplotlib/axis.py | 8 +++---- lib/matplotlib/backends/backend_gdk.py | 2 +- lib/matplotlib/backends/backend_ps.py | 5 +---- lib/matplotlib/cm.py | 10 ++++----- lib/matplotlib/table.py | 9 ++++---- lib/mpl_toolkits/mplot3d/proj3d.py | 6 +++--- 10 files changed, 38 insertions(+), 59 deletions(-) diff --git a/doc/api/api_changes/code_removal.rst b/doc/api/api_changes/code_removal.rst index 9d121bea160e..991240cac0e1 100644 --- a/doc/api/api_changes/code_removal.rst +++ b/doc/api/api_changes/code_removal.rst @@ -35,3 +35,9 @@ favor of the synonym ``"auto"``. The ``shading`` kwarg to ``pcolor`` has been removed. Set ``edgecolors`` appropriately instead. + +Removed internal functions +-------------------------- + +The ``matplotlib.backends.backend_ps.seq_allequal`` function has been removed. +Use ``np.array_equal`` instead. diff --git a/examples/misc/multiprocess.py b/examples/misc/multiprocess.py index a32a0f02fdf3..05cd7953c4bb 100644 --- a/examples/misc/multiprocess.py +++ b/examples/misc/multiprocess.py @@ -28,21 +28,15 @@ def terminate(self): def poll_draw(self): def call_back(): - while True: - if not self.pipe.poll(): - break - + while self.pipe.poll(): command = self.pipe.recv() - if command is None: self.terminate() return False - else: self.x.append(command[0]) self.y.append(command[1]) self.ax.plot(self.x, self.y, 'ro') - self.fig.canvas.draw() return True diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 89e7e2381164..3dc98c3399f3 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -107,6 +107,7 @@ import distutils.version from itertools import chain +from collections import MutableMapping import io import inspect import locale @@ -870,7 +871,7 @@ def matplotlib_fname(): _obsolete_set)) -class RcParams(dict): +class RcParams(MutableMapping, dict): """ A dictionary object including validation @@ -891,8 +892,7 @@ class RcParams(dict): # validate values on the way in def __init__(self, *args, **kwargs): - for k, v in six.iteritems(dict(*args, **kwargs)): - self[k] = v + self.update(*args, **kwargs) def __setitem__(self, key, val): try: @@ -942,16 +942,6 @@ def __getitem__(self, key): else: return val - # http://stackoverflow.com/questions/2390827 - # (how-to-properly-subclass-dict-and-override-get-set) - # the default dict `update` does not use __setitem__ - # so rcParams.update(...) (such as in seaborn) side-steps - # all of the validation over-ride update to force - # through __setitem__ - def update(self, *args, **kwargs): - for k, v in six.iteritems(dict(*args, **kwargs)): - self[k] = v - def __repr__(self): import pprint class_name = self.__class__.__name__ @@ -965,17 +955,12 @@ def __str__(self): return '\n'.join('{0}: {1}'.format(k, v) for k, v in sorted(self.items())) - def keys(self): - """ - Return sorted list of keys. - """ - return sorted(self) - - def values(self): + def __iter__(self): """ - Return values in order of sorted keys. + Yield sorted list of keys. """ - return [self[k] for k in self] + for k in sorted(dict.__iter__(self)): + yield k def find_all(self, pattern): """ diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 905a9bdd86aa..07f22d311157 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -9,7 +9,7 @@ import itertools import warnings import math -from operator import itemgetter +from operator import attrgetter import numpy as np @@ -396,9 +396,7 @@ def _plot_args(self, tup, kwargs): return ret def _grab_next_args(self, *args, **kwargs): - while True: - if not args: - return + while args: this, args = args[:2], args[2:] if args and is_string_like(args[0]): this += args[0], @@ -2357,18 +2355,18 @@ def draw(self, renderer=None, inframe=False): if not self.figure.canvas.is_saving(): artists = [a for a in artists if not a.get_animated() or a in self.images] - artists = sorted(artists, key=lambda artist: artist.get_zorder()) + artists = sorted(artists, key=attrgetter('zorder')) # rasterize artists with negative zorder # if the minimum zorder is negative, start rasterization rasterization_zorder = self._rasterization_zorder if (rasterization_zorder is not None and - artists and artists[0].get_zorder() < rasterization_zorder): + artists and artists[0].zorder < rasterization_zorder): renderer.start_rasterizing() artists_rasterized = [a for a in artists - if a.get_zorder() < rasterization_zorder] + if a.zorder < rasterization_zorder] artists = [a for a in artists - if a.get_zorder() >= rasterization_zorder] + if a.zorder >= rasterization_zorder] else: artists_rasterized = [] diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 60dcdb9821ca..2745721f1ebd 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -952,9 +952,9 @@ def _update_ticks(self, renderer): interval = self.get_view_interval() tick_tups = list(self.iter_ticks()) - if self._smart_bounds: + if self._smart_bounds and tick_tups: # handle inverted limits - view_low, view_high = min(interval), max(interval) + view_low, view_high = sorted(interval) data_low, data_high = sorted(self.get_data_interval()) locs = np.sort([ti[1] for ti in tick_tups]) if data_low <= view_low: @@ -963,7 +963,7 @@ def _update_ticks(self, renderer): else: # data stops within view, take best tick good_locs = locs[locs <= data_low] - if len(good_locs) > 0: + if len(good_locs): # last tick prior or equal to first data point ilow = good_locs[-1] else: @@ -975,7 +975,7 @@ def _update_ticks(self, renderer): else: # data stops within view, take best tick good_locs = locs[locs >= data_high] - if len(good_locs) > 0: + if len(good_locs): # first tick after or equal to last data point ihigh = good_locs[0] else: diff --git a/lib/matplotlib/backends/backend_gdk.py b/lib/matplotlib/backends/backend_gdk.py index 2b60faa76f2e..23133503df75 100644 --- a/lib/matplotlib/backends/backend_gdk.py +++ b/lib/matplotlib/backends/backend_gdk.py @@ -36,7 +36,7 @@ def fn_name(): return sys._getframe(1).f_code.co_name _debug = False # Image formats that this backend supports - for FileChooser and print_figure() -IMAGE_FORMAT = sorted(['eps', 'jpg', 'png', 'ps', 'svg'] + ['bmp']) # , 'raw', 'rgb'] +IMAGE_FORMAT = sorted(['bmp', 'eps', 'jpg', 'png', 'ps', 'svg']) # 'raw', 'rgb' IMAGE_FORMAT_DEFAULT = 'png' diff --git a/lib/matplotlib/backends/backend_ps.py b/lib/matplotlib/backends/backend_ps.py index e798e149179b..871f2a95b927 100644 --- a/lib/matplotlib/backends/backend_ps.py +++ b/lib/matplotlib/backends/backend_ps.py @@ -170,9 +170,6 @@ def quote_ps_string(s): return s.decode('ascii') -seq_allequal = np.array_equal - - class RendererPS(RendererBase): """ The renderer handles all the drawing primitives using a graphics @@ -256,7 +253,7 @@ def set_linecap(self, linecap, store=1): def set_linedash(self, offset, seq, store=1): if self.linedash is not None: oldo, oldseq = self.linedash - if seq_allequal(seq, oldseq) and oldo == offset: + if np.array_equal(seq, oldseq) and oldo == offset: return if seq is not None and len(seq): diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index e26d22c1f7ef..adc2c14b824c 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -85,12 +85,12 @@ def _generate_cmap(name, lutsize): # spectral/spectral_r when this module is imported. with _warnings.catch_warnings(): _warnings.simplefilter("ignore") - # Generate the reversed specifications ... - for cmapname, spec in list(six.iteritems(datad)): - datad[cmapname + '_r'] = _reverse_cmap_spec(spec) - - # Precache the cmaps with ``lutsize = LUTSIZE`` ... + # Generate the reversed specifications (all at once, to avoid + # modify-when-iterating). + datad.update({cmapname + '_r': _reverse_cmap_spec(spec) + for cmapname, spec in six.iteritems(datad)}) + # Precache the cmaps with ``lutsize = LUTSIZE``. # Also add the reversed ones added in the section above: for cmapname in datad: cmap_d[cmapname] = _generate_cmap(cmapname, LUTSIZE) diff --git a/lib/matplotlib/table.py b/lib/matplotlib/table.py index ebd4d760b06a..aa145170d565 100644 --- a/lib/matplotlib/table.py +++ b/lib/matplotlib/table.py @@ -287,7 +287,7 @@ def add_cell(self, row, col, *args, **kwargs): cell.set_transform(self.get_transform()) cell.set_clip_on(False) - self._cells[(row, col)] = cell + self._cells[row, col] = cell self.stale = True @property @@ -327,9 +327,9 @@ def _get_grid_bbox(self, renderer): """Get a bbox, in axes co-ordinates for the cells. Only include those in the range (0,0) to (maxRow, maxCol)""" - boxes = [self._cells[pos].get_window_extent(renderer) - for pos in self._cells if pos[0] >= 0 and pos[1] >= 0] - + boxes = [cell.get_window_extent(renderer) + for (row, col), cell in six.iteritems(self._cells) + if row >= 0 and col >= 0] bbox = Bbox.union(boxes) return bbox.inverse_transformed(self.get_transform()) @@ -362,7 +362,6 @@ def get_window_extent(self, renderer): 'Return the bounding box of the table in window coords' boxes = [cell.get_window_extent(renderer) for cell in six.itervalues(self._cells)] - return Bbox.union(boxes) def _do_cell_alignment(self): diff --git a/lib/mpl_toolkits/mplot3d/proj3d.py b/lib/mpl_toolkits/mplot3d/proj3d.py index 55162f58e70b..a24d44aa045b 100644 --- a/lib/mpl_toolkits/mplot3d/proj3d.py +++ b/lib/mpl_toolkits/mplot3d/proj3d.py @@ -134,9 +134,9 @@ def proj_transform_vec(vec, M): def proj_transform_vec_clip(vec, M): vecw = np.dot(M, vec) w = vecw[3] - # clip here.. - txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w - tis = (vecw[0] >= 0) & (vecw[0] <= 1) & (vecw[1] >= 0) & (vecw[1] <= 1) + # clip here. + txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w + tis = (0 <= vecw[0]) & (vecw[0] <= 1) & (0 <= vecw[1]) & (vecw[1] <= 1) if np.any(tis): tis = vecw[1] < 1 return txs, tys, tzs, tis