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

Merged
merged 9 commits into from Dec 22, 2016
Jump to file
+414 −736
Split
@@ -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.
@@ -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)
View
@@ -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("""\
@@ -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)):
View
@@ -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)
@@ -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):
"""
@@ -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))))
@@ -28,21 +28,15 @@ def terminate(self):
def poll_draw(self):
def call_back():
- while 1:
- 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
@@ -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()
@@ -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)]
@@ -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)
@@ -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
@@ -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
@@ -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(
@NelleV

NelleV Dec 19, 2016

Contributor

👍

+ 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:
@@ -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:
@@ -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"))
View
@@ -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:
@@ -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
@@ -941,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__
@@ -964,19 +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.
- """
- k = list(dict.keys(self))
- k.sort()
- return k
-
- 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.keys()]
+ for k in sorted(dict.__iter__(self)):
+ yield k
def find_all(self, pattern):
"""
@@ -1896,4 +1880,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')
Oops, something went wrong.