Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bfda3a4

Browse files
authored
Merge pull request #14750 from anntzer/appendless
Misc. simplifications.
2 parents 3239872 + 5a99918 commit bfda3a4

File tree

14 files changed

+54
-121
lines changed

14 files changed

+54
-121
lines changed

examples/event_handling/pipong.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,8 @@ def __init__(self, ax):
169169
self.on = False
170170
self.inst = True # show instructions from the beginning
171171
self.background = None
172-
self.pads = []
173-
self.pads.append(Pad(pA, padAx, padAy))
174-
self.pads.append(Pad(pB, padBx, padBy, 'r'))
172+
self.pads = [Pad(pA, padAx, padAy),
173+
Pad(pB, padBx, padBy, 'r')]
175174
self.pucks = []
176175
self.i = self.ax.annotate(instructions, (.5, 0.5),
177176
name='monospace',

examples/statistics/errorbars_and_boxes.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,9 @@
4242
def make_error_boxes(ax, xdata, ydata, xerror, yerror, facecolor='r',
4343
edgecolor='None', alpha=0.5):
4444

45-
# Create list for all the error patches
46-
errorboxes = []
47-
4845
# Loop over data points; create box from errors at each point
49-
for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T):
50-
rect = Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
51-
errorboxes.append(rect)
46+
errorboxes = [Rectangle((x - xe[0], y - ye[0]), xe.sum(), ye.sum())
47+
for x, y, xe, ye in zip(xdata, ydata, xerror.T, yerror.T)]
5248

5349
# Create patch collection with specified colour/alpha
5450
pc = PatchCollection(errorboxes, facecolor=facecolor, alpha=alpha,

examples/units/evans_test.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,10 @@ def default_units(x, axis):
6969
units.registry[Foo] = FooConverter()
7070

7171
# create some Foos
72-
x = []
73-
for val in range(0, 50, 2):
74-
x.append(Foo(val, 1.0))
75-
72+
x = [Foo(val, 1.0) for val in range(0, 50, 2)]
7673
# and some arbitrary y data
7774
y = [i for i in range(len(x))]
7875

79-
8076
fig, (ax1, ax2) = plt.subplots(1, 2)
8177
fig.suptitle("Custom units")
8278
fig.subplots_adjust(bottom=0.2)

lib/matplotlib/axes/_axes.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5056,11 +5056,9 @@ def fill(self, *args, data=None, **kwargs):
50565056
"""
50575057
# For compatibility(!), get aliases from Line2D rather than Patch.
50585058
kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
5059-
5060-
patches = []
5061-
for poly in self._get_patches_for_fill(*args, data=data, **kwargs):
5059+
patches = [*self._get_patches_for_fill(*args, data=data, **kwargs)]
5060+
for poly in patches:
50625061
self.add_patch(poly)
5063-
patches.append(poly)
50645062
self._request_autoscale_view()
50655063
return patches
50665064

lib/matplotlib/axes/_base.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,6 @@ def _makefill(self, x, y, kw, kwargs):
308308
return seg
309309

310310
def _plot_args(self, tup, kwargs):
311-
ret = []
312311
if len(tup) > 1 and isinstance(tup[-1], str):
313312
linestyle, marker, color = _process_plot_format(tup[-1])
314313
tup = tup[:-1]
@@ -361,10 +360,8 @@ def _plot_args(self, tup, kwargs):
361360
cbook.warn_deprecated(
362361
"2.2", message="cycling among columns of inputs with "
363362
"non-matching shapes is deprecated.")
364-
for j in range(max(ncx, ncy)):
365-
seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
366-
ret.append(seg)
367-
return ret
363+
return [func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
364+
for j in range(max(ncx, ncy))]
368365

369366

370367
class _AxesBase(martist.Artist):

lib/matplotlib/backend_tools.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,13 +1051,9 @@ def _format_tool_keymap(self, name):
10511051
return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
10521052

10531053
def _get_help_entries(self):
1054-
entries = []
1055-
for name, tool in sorted(self.toolmanager.tools.items()):
1056-
if not tool.description:
1057-
continue
1058-
entries.append((name, self._format_tool_keymap(name),
1059-
tool.description))
1060-
return entries
1054+
return [(name, self._format_tool_keymap(name), tool.description)
1055+
for name, tool in sorted(self.toolmanager.tools.items())
1056+
if tool.description]
10611057

10621058
def _get_help_text(self):
10631059
entries = self._get_help_entries()

lib/matplotlib/backends/backend_pgf.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,7 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
687687
writeln(self.fh, r"\pgfsetfillcolor{textcolor}")
688688
s = r"\color{textcolor}" + s
689689

690-
f = 1.0 / self.figure.dpi
690+
dpi = self.figure.dpi
691691
text_args = []
692692
if mtext and (
693693
(angle == 0 or
@@ -697,20 +697,18 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
697697
# and add alignment information
698698
pos = mtext.get_unitless_position()
699699
x, y = mtext.get_transform().transform(pos)
700-
text_args.append("x=%fin" % (x * f))
701-
text_args.append("y=%fin" % (y * f))
702-
703700
halign = {"left": "left", "right": "right", "center": ""}
704701
valign = {"top": "top", "bottom": "bottom",
705702
"baseline": "base", "center": ""}
706-
text_args.append(halign[mtext.get_horizontalalignment()])
707-
text_args.append(valign[mtext.get_verticalalignment()])
703+
text_args.extend([
704+
f"x={x/dpi}in",
705+
f"y={y/dpi}in",
706+
halign[mtext.get_horizontalalignment()],
707+
valign[mtext.get_verticalalignment()],
708+
])
708709
else:
709-
# if not, use the text layout provided by matplotlib
710-
text_args.append("x=%fin" % (x * f))
711-
text_args.append("y=%fin" % (y * f))
712-
text_args.append("left")
713-
text_args.append("base")
710+
# if not, use the text layout provided by Matplotlib.
711+
text_args.append(f"x={x/dpi}in, y={y/dpi}in, left, base")
714712

715713
if angle != 0:
716714
text_args.append("rotate=%f" % angle)

lib/matplotlib/table.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -227,16 +227,11 @@ def visible_edges(self, value):
227227
def get_path(self):
228228
"""Return a `.Path` for the `.visible_edges`."""
229229
codes = [Path.MOVETO]
230-
231-
for edge in self._edges:
232-
if edge in self._visible_edges:
233-
codes.append(Path.LINETO)
234-
else:
235-
codes.append(Path.MOVETO)
236-
230+
codes.extend(
231+
Path.LINETO if edge in self._visible_edges else Path.MOVETO
232+
for edge in self._edges)
237233
if Path.MOVETO not in codes[1:]: # All sides are visible
238234
codes[-1] = Path.CLOSEPOLY
239-
240235
return Path(
241236
[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
242237
codes,

lib/matplotlib/testing/jpl_units/StrConverter.py

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,7 @@ def convert(value, unit, axis):
7979
if v not in labels and v not in newValues:
8080
newValues.append(v)
8181

82-
for v in newValues:
83-
if labels:
84-
labels.append(v)
85-
else:
86-
labels = [v]
82+
labels.extend(newValues)
8783

8884
# DISABLED: This is disabled because matplotlib bar plots do not
8985
# DISABLED: recalculate the unit conversion of the data values
@@ -113,14 +109,7 @@ def convert(value, unit, axis):
113109
else:
114110
ax.set_ylim(ticks[0], ticks[-1])
115111

116-
result = []
117-
for v in value:
118-
# If v is not in labels then something went wrong with adding new
119-
# labels to the list of old labels.
120-
errmsg = "This is due to a logic error in the StrConverter class."
121-
errmsg += " Please report this error and its message in bugzilla."
122-
assert v in labels, errmsg
123-
result.append(ticks[labels.index(v)])
112+
result = [ticks[labels.index(v)] for v in value]
124113

125114
ax.viewLim.ignore(-1)
126115
return result

lib/matplotlib/tests/test_mathtext.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -145,15 +145,14 @@
145145

146146
font_tests = []
147147
for fonts, chars in font_test_specs:
148-
wrapper = [' '.join(fonts), ' $']
149-
for font in fonts:
150-
wrapper.append(r'\%s{' % font)
151-
wrapper.append('%s')
152-
for font in fonts:
153-
wrapper.append('}')
154-
wrapper.append('$')
155-
wrapper = ''.join(wrapper)
156-
148+
wrapper = ''.join([
149+
' '.join(fonts),
150+
' $',
151+
*(r'\%s{' % font for font in fonts),
152+
'%s',
153+
*('}' for font in fonts),
154+
'$',
155+
])
157156
for set in chars:
158157
font_tests.append(wrapper % set)
159158

lib/matplotlib/tight_layout.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,9 @@ def auto_adjust_subplotpars(
9696
union = Bbox.union
9797

9898
if ax_bbox_list is None:
99-
ax_bbox_list = []
100-
for subplots in subplot_list:
101-
ax_bbox = union([ax.get_position(original=True)
102-
for ax in subplots])
103-
ax_bbox_list.append(ax_bbox)
99+
ax_bbox_list = [
100+
union([ax.get_position(original=True) for ax in subplots])
101+
for subplots in subplot_list]
104102

105103
for subplots, ax_bbox, (num1, num2) in zip(subplot_list,
106104
ax_bbox_list,

lib/matplotlib/widgets.py

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
wide and tall you want your Axes to be to accommodate your widget.
1010
"""
1111

12+
from contextlib import ExitStack
1213
import copy
1314
from numbers import Integral
1415

@@ -1194,26 +1195,16 @@ def __init__(self, targetfig, toolfig):
11941195
self.slidertop, self.sliderwspace, self.sliderhspace,)
11951196

11961197
def func(event):
1197-
thisdrawon = self.drawon
1198-
1199-
self.drawon = False
1200-
1201-
# store the drawon state of each slider
1202-
bs = []
1203-
for slider in sliders:
1204-
bs.append(slider.drawon)
1205-
slider.drawon = False
1206-
1207-
# reset the slider to the initial position
1208-
for slider in sliders:
1209-
slider.reset()
1210-
1211-
# reset drawon
1212-
for slider, b in zip(sliders, bs):
1213-
slider.drawon = b
1214-
1215-
# draw the canvas
1216-
self.drawon = thisdrawon
1198+
with ExitStack() as stack:
1199+
# Temporarily disable drawing on self and self's sliders.
1200+
stack.enter_context(cbook._setattr_cm(self, drawon=False))
1201+
for slider in sliders:
1202+
stack.enter_context(
1203+
cbook._setattr_cm(slider, drawon=False))
1204+
# Reset the slider to the initial position.
1205+
for slider in sliders:
1206+
slider.reset()
1207+
# Draw the canvas.
12171208
if self.drawon:
12181209
toolfig.canvas.draw()
12191210
self.targetfig.canvas.draw()

lib/mpl_toolkits/axes_grid1/axes_divider.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -91,14 +91,9 @@ def _calc_k(l, total_size):
9191

9292
@staticmethod
9393
def _calc_offsets(l, k):
94-
9594
offsets = [0.]
96-
97-
#for s in l:
9895
for _rs, _as in l:
99-
#_rs, _as = s.get_size(renderer)
10096
offsets.append(offsets[-1] + _rs*k + _as)
101-
10297
return offsets
10398

10499
def set_position(self, pos):
@@ -703,11 +698,8 @@ def _determine_karray(equivalent_sizes, appended_sizes,
703698
@staticmethod
704699
def _calc_offsets(appended_sizes, karray):
705700
offsets = [0.]
706-
707-
#for s in l:
708701
for (r, a), k in zip(appended_sizes, karray):
709702
offsets.append(offsets[-1] + r*k + a)
710-
711703
return offsets
712704

713705
def new_locator(self, nx, nx1=None):

lib/mpl_toolkits/mplot3d/art3d.py

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -627,25 +627,15 @@ def set_zsort(self, zsort):
627627

628628
def get_vector(self, segments3d):
629629
"""Optimize points for projection."""
630-
si = 0
631-
ei = 0
632-
segis = []
633-
points = []
634-
for p in segments3d:
635-
points.extend(p)
636-
ei = si + len(p)
637-
segis.append((si, ei))
638-
si = ei
639-
640630
if len(segments3d):
641-
xs, ys, zs = zip(*points)
642-
else:
643-
# We need this so that we can skip the bad unpacking from zip()
631+
xs, ys, zs = np.row_stack(segments3d).T
632+
else: # row_stack can't stack zero arrays.
644633
xs, ys, zs = [], [], []
645-
646634
ones = np.ones(len(xs))
647635
self._vec = np.array([xs, ys, zs, ones])
648-
self._segis = segis
636+
637+
indices = [0, *np.cumsum([len(segment) for segment in segments3d])]
638+
self._segslices = [*map(slice, indices[:-1], indices[1:])]
649639

650640
def set_verts(self, verts, closed=True):
651641
"""Set 3D vertices."""
@@ -688,8 +678,7 @@ def do_3d_projection(self, renderer):
688678
self._facecolors3d = self._facecolors
689679

690680
txs, tys, tzs = proj3d._proj_transform_vec(self._vec, renderer.M)
691-
xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei])
692-
for si, ei in self._segis]
681+
xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices]
693682

694683
# This extra fuss is to re-order face / edge colors
695684
cface = self._facecolors3d

0 commit comments

Comments
 (0)