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
Next Next commit
dict.keys() is nearly always useless.
  • Loading branch information
anntzer committed Dec 21, 2016
commit 39352a87b4e1094f28746409f310b5d2d681e1ed
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
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()
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
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
7 changes: 4 additions & 3 deletions lib/matplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 Down Expand Up @@ -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]
Copy link
Member

Choose a reason for hiding this comment

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

Does dropping .keys() and iterating over self correctly preserve the sorted order that the keys method from this subclass produces?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No. But that also means that iteration on the dict itself (for k in rcparams) happens in a different order right now...


def find_all(self, pattern):
"""
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/afm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backend_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/markers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))

Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/mlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/offsetbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down Expand Up @@ -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",
Expand Down
5 changes: 1 addition & 4 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2096,7 +2096,7 @@ def colormaps():


"""
return sorted(cm.cmap_d.keys())
return sorted(cm.cmap_d)


def _setup_pyplot_info_docstrings():
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/style/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
2 changes: 1 addition & 1 deletion lib/matplotlib/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_arrow_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
59 changes: 11 additions & 48 deletions lib/matplotlib/tests/test_cbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading