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
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}}$'),

0 commit comments

Comments
 (0)