8000 MAINT Use list comprehension by rth · Pull Request #12883 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

MAINT Use list comprehension #12883

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 5 commits into from
Nov 26, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
5 changes: 1 addition & 4 deletions lib/matplotlib/_pylab_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,7 @@ def set_active(cls, manager):
Make the figure corresponding to *manager* the active one.
"""
oldQue = cls._activeQue[:]
cls._activeQue = []
for m in oldQue:
if m != manager:
cls._activeQue.append(m)
cls._activeQue = [m for m in oldQue if m != manager]
cls._activeQue.append(manager)
cls.figs[manager.num] = manager

Expand Down
7 changes: 3 additions & 4 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,9 @@ def ensure_not_dirty(self):

def reset_available_writers(self):
"""Reset the available state of all registered writers"""
self.avail = {}
for name, writerClass in self._registered.items():
if writerClass.isAvailable():
self.avail[name] = writerClass
self.avail = {name: writerClass
for name, writerClass in self._registered.items()
if writerClass.isAvailable()}
self._dirty = False

def list(self):
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,10 @@ def draw_path_collection(self, gc, master_transform, paths, all_transforms,
recommended to use those generators, so that changes to the
behavior of :meth:`draw_path_collection` can be made globally.
"""
path_ids = []
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms):
path_ids.append((path, transforms.Affine2D(transform)))
path_ids = [
(path, transforms.Affine2D(transform))
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms)]

for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
gc, master_transform, all_transforms, path_ids, offsets,
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_cairo.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,10 @@ def draw_path_collection(
offsetTrans, facecolors, edgecolors, linewidths, linestyles,
antialiaseds, urls, offset_position):

path_ids = []
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms):
path_ids.append((path, Affine2D(transform)))
path_ids = [
(path, Affine2D(transform))
for path, transform in self._iter_collection_raw_paths(
master_transform, paths, all_transforms)]

reuse_key = None
grouped_draw = []
Expand Down
5 changes: 1 addition & 4 deletions lib/matplotlib/backends/backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -1097,10 +1097,7 @@ def print_figure_impl(fh):
ps_renderer.used_characters.values():
if len(chars):
font = get_font(font_filename)
glyph_ids = []
for c in chars:
gind = font.get_char_index(c)
glyph_ids.append(gind)
glyph_ids = [font.get_char_index(c) for c in chars]

fonttype = rcParams['ps.fonttype']

Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/backends/backend_wx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,10 +1439,8 @@ def updateAxes(self, maxAxis):

def getActiveAxes(self):
"""Return a list of the selected axes."""
active = []
for i in range(len(self._axisId)):
if self._menu.IsChecked(self._axisId[i]):
active.append(i)
active = [idx for idx, ax_id in enumerate(self._axisId)
if self._menu.IsChecked(ax_id)]
return active

def updateButtonText(self, lst):
Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/collections.py
< 57AE /tr>
Original file line number Diff line number Diff line change
Expand Up @@ -1402,9 +1402,7 @@ def get_positions(self):
'''
segments = self.get_segments()
pos = 0 if self.is_horizontal() else 1
positions = []
for segment in segments:
positions.append(segment[0, pos])
positions = [segment[0, pos] for segment in segments]
return positions

def set_positions(self, positions):
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/legend_handler.py
B41A
Original file line number Diff line number Diff line change
Expand Up @@ -606,10 +606,8 @@ def create_artists(self, legend, orig_handle,
leg_markerline = Line2D(xdata_marker, ydata[:len(xdata_marker)])
self.update_prop(leg_markerline, markerline, legend)

leg_stemlines = []
for thisx, thisy in zip(xdata_marker, ydata):
l = Line2D([thisx, thisx], [bottom, thisy])
leg_stemlines.append(l)
leg_stemlines = [Line2D([thisx, thisx], [bottom, thisy])
for thisx, thisy in zip(xdata_marker, ydata)]
Copy link
Member

Choose a reason for hiding this comment

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

The "this" prefix doesn't add any information and just makes it harder to read. While you're at it, can you please change this to for x, y in ...? That would further improve the code.


for lm, m in zip(leg_stemlines, stemlines):
self.update_prop(lm, m, legend)
Expand Down
20 changes: 7 additions & 13 deletions lib/mpl_toolkits/mplot3d/art3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,14 +189,11 @@ def path_to_3d_segment_with_codes(path, zs=0, zdir='z'):
"""Convert a path to a 3D segment with path codes."""

zs = np.broadcast_to(zs, len(path))
seg = []
codes = []
pathsegs = path.iter_segments(simplify=False, curves=False)
for (((x, y), code), z) in zip(pathsegs, zs):
seg.append((x, y, z))
codes.append(code)
seg, codes = zip(
*[((x, y, z), code) for (((x, y), code), z) in zip(pathsegs, zs)])
seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg]
return seg3d, codes
return seg3d, list(codes)


def paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'):
Expand All @@ -205,13 +202,10 @@ def paths_to_3d_segments_with_codes(paths, zs=0, zdir=&# D208 39;z'):
"""

zs = np.broadcast_to(zs, len(paths))
segments = []
codes_list = []
for path, pathz in zip(paths, zs):
segs, codes = path_to_3d_segment_with_codes(path, pathz, zdir)
segments.append(segs)
codes_list.append(codes)
return segments, codes_list
segments, codes_list = zip(
*[path_to_3d_segment_with_codes(path, pathz, zdir)
for path, pathz in zip(paths, zs)])
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Related to #11577, this should be faster,

In [4]: sequence = list(zip(range(1000), range(1000)))                                                                                                       

In [5]: %%timeit 
   ...: x = [] 
   ...: y = [] 
   ...: for x_el, y_el in sequence: 
   ...:     x.append(x_el) 
   ...:     y.append(y_el) 
   ...:                                                                                                                                                      
135 µs ± 498 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [6]: %%timeit 
   ...: x, y = zip(*sequence) 
   ...: x = list(x) 
   ...: y = list(y) 
   ...:  
   ...:                                                                                                                                                      
49.2 µs ± 234 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Copy link
Member

Choose a reason for hiding this comment

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

This is indeed a good performance improvement! However, it gets hard to read because there's too much going on. I propose to construct the list beforehand and give it a name. This should be equally fast.

    segments_and_codes_list = [
        path_to_3d_segment_with_codes(path, pathz, zdir)
        for path, pathz in zip(paths, zs)
    ]
    segments, codes = zip(*segments_and_codes_list)
    return list(segments), list(codes)

return list(segments), list(codes_list)


class Line3DCollection(LineCollection):
Expand Down
0