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
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.
2 changes: 1 addition & 1 deletion doc/sphinxext/gen_gallery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions doc/sphinxext/gen_rst.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("""\
Expand Down
8 changes: 2 additions & 6 deletions doc/sphinxext/math_symbol_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)):
Expand Down
10 changes: 3 additions & 7 deletions doc/utils/pylab_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
5 changes: 3 additions & 2 deletions examples/api/custom_projection_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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):
"""
Expand Down
3 changes: 1 addition & 2 deletions examples/api/custom_scale_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))))
Expand Down
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 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

Expand Down
6 changes: 3 additions & 3 deletions examples/pylab_examples/fancybox_demo2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
3 changes: 1 addition & 2 deletions examples/pylab_examples/font_table_ttf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
2 changes: 1 addition & 1 deletion examples/pylab_examples/tex_unicode_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion examples/statistics/bxp_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion examples/statistics/errorbar_limits.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 2 additions & 5 deletions examples/style_sheets/style_sheets_reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

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:
Expand Down
4 changes: 2 additions & 2 deletions examples/units/basic_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
12 changes: 5 additions & 7 deletions examples/user_interfaces/toolmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
38 changes: 11 additions & 27 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 All @@ -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
Expand All @@ -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__
Expand All @@ -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):
"""
Expand Down Expand Up @@ -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')
Loading