Skip to content

Cleanup: sorted, dict iteration, array.{ndim,size}, ... #7549

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Dec 22, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
More cleanups following PR comments.
  • Loading branch information
anntzer committed Dec 21, 2016
commit 14b47baf5c2835bb139ddec794c96044a803ac50
6 changes: 6 additions & 0 deletions doc/api/api_changes/code_removal.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 1 addition & 7 deletions examples/misc/multiprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
29 changes: 7 additions & 22 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
import distutils.version
from itertools import chain

from collections import MutableMapping
import io
import inspect
import locale
Expand Down Expand Up @@ -870,7 +871,7 @@ def matplotlib_fname():
_obsolete_set))


class RcParams(dict):
class RcParams(MutableMapping, dict):

"""
A dictionary object including validation
Expand All @@ -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:
Expand Down Expand Up @@ -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__
Expand All @@ -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):
"""
Expand Down
14 changes: 6 additions & 8 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import itertools
import warnings
import math
from operator import itemgetter
from operator import attrgetter

import numpy as np

Expand Down Expand Up @@ -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],
Expand Down Expand Up @@ -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 = []

Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_gdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'


Expand Down
5 changes: 1 addition & 4 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
10 changes: 5 additions & 5 deletions lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 4 additions & 5 deletions lib/matplotlib/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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())

Expand Down Expand Up @@ -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):
Expand Down
6 changes: 3 additions & 3 deletions lib/mpl_toolkits/mplot3d/proj3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down