8000 Replace full list evaluations with more efficient calls · trygvrad/matplotlib@dbad6cf · GitHub
[go: up one dir, main page]

Skip to content

Commit dbad6cf

Browse files
committed
Replace full list evaluations with more efficient calls
- UP027: Replace unpacked list comprehensions with generator expressions; these are supposedly more efficient since no temporary list is created. - RUF015: Replace accessing the first element of an evaluated list with `next(iter(...))`, avoiding the temporary list. - RUF017: Replace quadratic `sum(list of list, [])` with faster `functools.reduce` implementation.
1 parent f734bb5 commit dbad6cf

18 files changed

+35
-32
lines changed

lib/matplotlib/_docstring.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,8 @@ def __missing__(self, key):
8282
name = key[:-len(":kwdoc")]
8383
from matplotlib.artist import Artist, kwdoc
8484
try:
85-
cls, = [cls for cls in _api.recursive_subclasses(Artist)
86-
if cls.__name__ == name]
85+
cls, = (cls for cls in _api.recursive_subclasses(Artist)
86+
if cls.__name__ == name)
8787
except ValueError as e:
8888
raise KeyError(key) from e
8989
return self.setdefault(key, kwdoc(cls))

lib/matplotlib/_mathtext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float,
376376
font.set_size(fontsize, dpi)
377377
glyph = font.load_char(num, flags=self.load_glyph_flags)
378378

379-
xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
379+
xmin, ymin, xmax, ymax = (val / 64 for val in glyph.bbox)
380380
offset = self._get_offset(font, glyph, fontsize, dpi)
381381
metrics = FontMetrics(
382382
advance = glyph.linearHoriAdvance/65536.0,

lib/matplotlib/artist.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
from collections import namedtuple
22
import contextlib
3-
from functools import cache, wraps
3+
from functools import cache, reduce, wraps
44
import inspect
55
from inspect import Signature, Parameter
66
import logging
77
from numbers import Number, Real
8+
import operator
89
import re
910
import warnings
1011

@@ -1290,7 +1291,8 @@ def matchfunc(x):
12901291
raise ValueError('match must be None, a matplotlib.artist.Artist '
12911292
'subclass, or a callable')
12921293

1293-
artists = sum([c.findobj(matchfunc) for c in self.get_children()], [])
1294+
artists = reduce(operator.iadd,
1295+
[c.findobj(matchfunc) for c in self.get_children()], [])
12941296
if include_self and matchfunc(self):
12951297
artists.append(self)
12961298
return artists

lib/matplotlib/axes/_axes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6000,7 +6000,7 @@ def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):
60006000
# unit conversion allows e.g. datetime objects as axis values
60016001
X, Y = args[:2]
60026002
X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs)
6003-
X, Y = [cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]]
6003+
X, Y = (cbook.safe_masked_invalid(a, copy=True) for a in [X, Y])
60046004

60056005
if funcname == 'pcolormesh':
60066006
if np.ma.is_masked(X) or np.ma.is_masked(Y):

lib/matplotlib/axis.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
# allows all Line2D kwargs.
3030
_line_inspector = martist.ArtistInspector(mlines.Line2D)
3131
_line_param_names = _line_inspector.get_setters()
32-
_line_param_aliases = [list(d)[0] for d in _line_inspector.aliasd.values()]
32+
_line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()]
3333
_gridline_param_names = ['grid_' + name
3434
for name in _line_param_names + _line_param_aliases]
3535

@@ -728,8 +728,8 @@ def _get_shared_axis(self):
728728

729729
def _get_axis_name(self):
730730
"""Return the axis name."""
731-
return [name for name, axis in self.axes._axis_map.items()
732-
if axis is self][0]
731+
return next(name for name, axis in self.axes._axis_map.items()
732+
if axis is self)
733733

734734
# During initialization, Axis objects often create ticks that are later
735735
# unused; this turns out to be a very slow step. Instead, use a custom

lib/matplotlib/backends/backend_qt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -483,7 +483,7 @@ def blit(self, bbox=None):
483483
if bbox is None and self.figure:
484484
bbox = self.figure.bbox # Blit the entire canvas if bbox is None.
485485
# repaint uses logical pixels, not physical pixels like the renderer.
486-
l, b, w, h = [int(pt / self.device_pixel_ratio) for pt in bbox.bounds]
486+
l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds)
487487
t = b + h
488488 10000
self.repaint(l, self.rect().height() - t, w, h)
489489

@@ -504,7 +504,7 @@ def drawRectangle(self, rect):
504504
# Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
505505
# to be called at the end of paintEvent.
506506
if rect is not None:
507-
x0, y0, w, h = [int(pt / self.device_pixel_ratio) for pt in rect]
507+
x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect)
508508
x1 = x0 + w
509509
y1 = y0 + h
510510
def _draw_rect_callback(painter):

lib/matplotlib/backends/backend_wx.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1197,8 +1197,8 @@ def _get_tool_pos(self, tool):
11971197
``ToolBar.GetToolPos`` is not useful because wx assigns the same Id to
11981198
all Separators and StretchableSpaces.
11991199
"""
1200-
pos, = [pos for pos in range(self.ToolsCount)
1201-
if self.GetToolByPos(pos) == tool]
1200+
pos, = (pos for pos in range(self.ToolsCount)
1201+
if self.GetToolByPos(pos) == tool)
12021202
return pos
12031203

12041204
def add_toolitem(self, name, group, position, image_file, description,

lib/matplotlib/bezier.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def get_intersection(cx1, cy1, cos_t1, sin_t1,
5454
# rhs_inverse
5555
a_, b_ = d, -b
5656
c_, d_ = -c, a
57-
a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]
57+
a_, b_, c_, d_ = (k / ad_bc for k in [a_, b_, c_, d_])
5858

5959
x = a_ * line1_rhs + b_ * line2_rhs
6060
y = c_ * line1_rhs + d_ * line2_rhs

lib/matplotlib/quiver.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -424,13 +424,13 @@ def _parse_args(*args, caller_name='function'):
424424
X = X.ravel()
425425
Y = Y.ravel()
426426
if len(X) == nc and len(Y) == nr:
427-
X, Y = [a.ravel() for a in np.meshgrid(X, Y)]
427+
X, Y = (a.ravel() for a in np.meshgrid(X, Y))
428428
elif len(X) != len(Y):
429429
raise ValueError('X and Y must be the same size, but '
430430
f'X.size is {X.size} and Y.size is {Y.size}.')
431431
else:
432432
indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
433-
X, Y = [np.ravel(a) for a in indexgrid]
433+
X, Y = (np.ravel(a) for a in indexgrid)
434434
# Size validation for U, V, C is left to the set_UVC method.
435435
return X, Y, U, V, C
436436

lib/matplotlib/tests/test_axes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3086,10 +3086,10 @@ def test_log_scales():
30863086
ax.set_yscale('log', base=5.5)
30873087
ax.invert_yaxis()
30883088
ax.set_xscale('log', base=9.0)
3089-
xticks, yticks = [
3089+
xticks, yticks = (
30903090
[(t.get_loc(), t.label1.get_text()) for t in axis._update_ticks()]
30913091
for axis in [ax.xaxis, ax.yaxis]
3092-
]
3092+
)
30933093
assert xticks == [
30943094
(1.0, '$\\mathdefault{9^{0}}$'),
30953095
(9.0, '$\\mathdefault{9^{1}}$'),

lib/matplotlib/tests/test_font_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -183,8 +183,8 @@ def test_addfont_as_path():
183183
path = Path(__file__).parent / font_test_file
184184
try:
185185
fontManager.addfont(path)
186-
added, = [font for font in fontManager.ttflist
187-
if font.fname.endswith(font_test_file)]
186+
added, = (font for font in fontManager.ttflist
187+
if font.fname.endswith(font_test_file))
188188
fontManager.ttflist.remove(added)
189189
finally:
190190
to_remove = [font for font in fontManager.ttflist

lib/matplotlib/tests/test_mathtext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ def test_short_long_accents(fig_test, fig_ref):
270270
short_accs = [s for s in acc_map if len(s) == 1]
271271
corresponding_long_accs = []
272272
for s in short_accs:
273-
l, = [l for l in acc_map if len(l) > 1 and acc_map[l] == acc_map[s]]
273+
l, = (l for l in acc_map if len(l) > 1 and acc_map[l] == acc_map[s])
274274
corresponding_long_accs.append(l)
275275
fig_test.text(0, .5, "$" + "".join(rf"\{s}a" for s in short_accs) + "$")
276276
fig_ref.text(

lib/matplotlib/tests/test_sphinxext.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def plot_directive_file(num):
6262
# This is always next to the doctree dir.
6363
return doctree_dir.parent / 'plot_directive' / f'some_plots-{num}.png'
6464

65-
range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)]
65+
range_10, range_6, range_4 = (plot_file(i) for i in range(1, 4))
6666
# Plot 5 is range(6) plot
6767
assert filecmp.cmp(range_6, plot_file(5))
6868
# Plot 7 is range(4) plot

lib/matplotlib/tests/test_text.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -921,7 +921,7 @@ def test_annotate_offset_fontsize():
921921
fontsize='10',
922922
xycoords='data',
923923
textcoords=text_coords[i]) for i in range(2)]
924-
points_coords, fontsize_coords = [ann.get_window_extent() for ann in anns]
924+
points_coords, fontsize_coords = (ann.get_window_extent() for ann in anns)
925925
fig.canvas.draw()
926926
assert str(points_coords) == str(fontsize_coords)
927927

lib/matplotlib/tests/test_type1font.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,11 +141,11 @@ def test_overprecision():
141141
font = t1f.Type1Font(filename)
142142
slanted = font.transform({'slant': .167})
143143
lines = slanted.parts[0].decode('ascii').splitlines()
144-
matrix, = [line[line.index('[')+1:line.index(']')]
145-
for line in lines if '/FontMatrix' in line]
146-
angle, = [word
144+
matrix, = (line[line.index('[')+1:line.index(']')]
145+
for line in lines if '/FontMatrix' in line)
146+
angle, = (word
147147
for line in lines if '/ItalicAngle' in line
148-
for word in line.split() if word[0] in '-0123456789']
148+
for word in line.split() if word[0] in '-0123456789')
149149
# the following used to include 0.00016700000000000002
150150
assert matrix == '0.001 0 0.000167 0.001 0 0'
151151
# and here we had -9.48090361795083

lib/matplotlib/tests/test_widgets.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import functools
22
import io
3+
import operator
34
from unittest import mock
45

56
import matplotlib as mpl
@@ -1573,7 +1574,7 @@ def test_polygon_selector_remove(idx, draw_bounding_box):
15731574
# Remove the extra point
15741575
event_sequence.append(polygon_remove_vertex(200, 200))
15751576
# Flatten list of lists
1576-
event_sequence = sum(event_sequence, [])
1577+
event_sequence = functools.reduce(operator.iadd, event_sequence, [])
15771578
check_polygon_selector(event_sequence, verts, 2,
15781579
draw_bounding_box=draw_bounding_box)
15791580

lib/mpl_toolkits/mplot3d/tests/test_axes3d.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -508,10 +508,10 @@ def test_scatter3d_sorting(fig_ref, fig_test, depthshade):
508508
linewidths[0::2, 0::2] = 5
509509
linewidths[1::2, 1::2] = 5
510510

511-
x, y, z, sizes, facecolors, edgecolors, linewidths = [
511+
x, y, z, sizes, facecolors, edgecolors, linewidths = (
512512
a.flatten()
513513
for a in [x, y, z, sizes, facecolors, edgecolors, linewidths]
514-
]
514+
)
515515

516516
ax_ref = fig_ref.add_subplot(projection='3d')
517517
sets = (np.unique(a) for a in [sizes, facecolors, edgecolors, linewidths])

tools/generate_matplotlibrc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
backend = sys.argv[3]
2121

2222
template_lines = input.read_text(encoding="utf-8").splitlines(True)
23-
backend_line_idx, = [ # Also asserts that there is a single such line.
23+
backend_line_idx, = ( # Also asserts that there is a single such line.
2424
idx for idx, line in enumerate(template_lines)
25-
if "#backend:" in line]
25+
if "#backend:" in line)
2626
template_lines[backend_line_idx] = (
2727
f"#backend: {backend}\n" if backend not in ['', 'auto'] else "##backend: Agg\n")
2828
output.write_text("".join(template_lines), encoding="utf-8")

0 commit comments

Comments
 (0)
0