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

Skip to content

Commit 73a731b

Browse files
authored
Merge pull request #28599 from QuLogic/pyupgrade
Upgrade code to Python 3.10
2 parents 9c69c32 + 54c8491 commit 73a731b

38 files changed

+130
-127
lines changed

galleries/examples/showcase/stock_prices.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
'ADBE', 'GSPC', 'IXIC']
4343

4444
# Manually adjust the label positions vertically (units are points = 1/72 inch)
45-
y_offsets = {k: 0 for k in stocks_ticker}
45+
y_offsets = dict.fromkeys(stocks_ticker, 0)
4646
y_offsets['IBM'] = 5
4747
y_offsets['AAPL'] = -5
4848
y_offsets['AMZN'] = -6

galleries/examples/units/basic_units.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
88
"""
99

10+
import itertools
1011
import math
1112

1213
from packaging.version import parse as parse_version
@@ -254,7 +255,7 @@ def get_unit(self):
254255

255256
class UnitResolver:
256257
def addition_rule(self, units):
257-
for unit_1, unit_2 in zip(units[:-1], units[1:]):
258+
for unit_1, unit_2 in itertools.pairwise(units):
258259
if unit_1 != unit_2:
259260
return NotImplemented
260261
return units[0]

lib/matplotlib/_api/__init__.pyi

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
from collections.abc import Callable, Generator, Mapping, Sequence
2-
from typing import Any, Iterable, TypeVar, overload
1+
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
2+
from typing import Any, TypeVar, overload
33
from typing_extensions import Self # < Py 3.11
44

55
from numpy.typing import NDArray

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/_docstring.pyi

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from typing import Any, Callable, TypeVar, overload
1+
from collections.abc import Callable
2+
from typing import Any, TypeVar, overload
23

34

45
_T = TypeVar('_T')

lib/matplotlib/_mathtext.py

Lines changed: 3 additions & 3 deletions
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,
@@ -2645,7 +2645,7 @@ def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathSty
26452645
if rdelim == '':
26462646
rdelim = '.'
26472647
return self._auto_sized_delimiter(ldelim,
2648-
T.cast(list[T.Union[Box, Char, str]],
2648+
T.cast(list[Box | Char | str],
26492649
result),
26502650
rdelim)
26512651
return result
@@ -2786,7 +2786,7 @@ def _auto_sized_delimiter(self, front: str,
27862786
del middle[idx]
27872787
# There should only be \middle and its delimiter as str, which have
27882788
# just been removed.
2789-
middle_part = T.cast(list[T.Union[Box, Char]], middle)
2789+
middle_part = T.cast(list[Box | Char], middle)
27902790
else:
27912791
height = 0
27922792
depth = 0

lib/matplotlib/_mathtext_data.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"""
44

55
from __future__ import annotations
6-
from typing import overload, Union
6+
from typing import overload
77

88
latex_to_bakoma = {
99
'\\__sqrt__' : ('cmex10', 0x70),
@@ -1113,11 +1113,10 @@
11131113
# Each element is a 4-tuple of the form:
11141114
# src_start, src_end, dst_font, dst_start
11151115

1116-
_EntryTypeIn = tuple[str, str, str, Union[str, int]]
1116+
_EntryTypeIn = tuple[str, str, str, str | int]
11171117
_EntryTypeOut = tuple[int, int, str, int]
11181118

1119-
_stix_virtual_fonts: dict[str, Union[dict[
1120-
str, list[_EntryTypeIn]], list[_EntryTypeIn]]] = {
1119+
_stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeIn]] | list[_EntryTypeIn]] = {
11211120
'bb': {
11221121
"rm": [
11231122
("\N{DIGIT ZERO}",
@@ -1729,8 +1728,7 @@ def _normalize_stix_fontcodes(d):
17291728
return {k: _normalize_stix_fontcodes(v) for k, v in d.items()}
17301729

17311730

1732-
stix_virtual_fonts: dict[str, Union[dict[str, list[_EntryTypeOut]],
1733-
list[_EntryTypeOut]]]
1731+
stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]]
17341732
stix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts)
17351733

17361734
# Free redundant list now that it has been normalized

lib/matplotlib/animation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1086,8 +1086,8 @@ def _pre_composite_to_white(color):
10861086
# canvas._is_saving = True makes the draw_event animation-starting
10871087
# callback a no-op; canvas.manager = None prevents resizing the GUI
10881088
# widget (both are likewise done in savefig()).
1089-
with writer.saving(self._fig, filename, dpi), \
1090-
cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None):
1089+
with (writer.saving(self._fig, filename, dpi),
1090+
cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
10911091
for anim in all_anim:
10921092
anim._init_draw() # Clear the initial frame
10931093
frame_number = 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/axes/_base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ def __init__(self, fig,
646646
self._aspect = 'auto'
647647
self._adjustable = 'box'
648648
self._anchor = 'C'
649-
self._stale_viewlims = {name: False for name in self._axis_names}
649+
self._stale_viewlims = dict.fromkeys(self._axis_names, False)
650650
self._forward_navigation_events = forward_navigation_events
651651
self._sharex = sharex
652652
self._sharey = sharey

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/backend_bases.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1972,8 +1972,8 @@ def _switch_canvas_and_return_print_method(self, fmt, backend=None):
19721972
"""
19731973
Context manager temporarily setting the canvas for saving the figure::
19741974
1975-
with canvas._switch_canvas_and_return_print_method(fmt, backend) \\
1976-
as print_method:
1975+
with (canvas._switch_canvas_and_return_print_method(fmt, backend)
1976+
as print_method):
19771977
# ``print_method`` is a suitable ``print_{fmt}`` method, and
19781978
# the figure's canvas is temporarily switched to the method's
19791979
# canvas within the with... block. ``print_method`` is also
@@ -2110,13 +2110,13 @@ def print_figure(
21102110
"'figure', or omit the *papertype* argument entirely.")
21112111

21122112
# Remove the figure manager, if any, to avoid resizing the GUI widget.
2113-
with cbook._setattr_cm(self, manager=None), \
2114-
self._switch_canvas_and_return_print_method(format, backend) \
2115-
as print_method, \
2116-
cbook._setattr_cm(self.figure, dpi=dpi), \
2117-
cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1), \
2118-
cbook._setattr_cm(self.figure.canvas, _is_saving=True), \
2119-
ExitStack() as stack:
2113+
with (cbook._setattr_cm(self, manager=None),
2114+
self._switch_canvas_and_return_print_method(format, backend)
2115+
as print_method,
2116+
cbook._setattr_cm(self.figure, dpi=dpi),
2117+
cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1),
2118+
cbook._setattr_cm(self.figure.canvas, _is_saving=True),
2119+
ExitStack() as stack):
21202120

21212121
for prop in ["facecolor", "edgecolor"]:
21222122
color = locals()[prop]

lib/matplotlib/backend_tools.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -382,8 +382,8 @@ def trigger(self, sender, event, data=None):
382382
sentinel = str(uuid.uuid4())
383383
# Trigger grid switching by temporarily setting :rc:`keymap.grid`
384384
# to a unique key and sending an appropriate event.
385-
with cbook._setattr_cm(event, key=sentinel), \
386-
mpl.rc_context({'keymap.grid': sentinel}):
385+
with (cbook._setattr_cm(event, key=sentinel),
386+
mpl.rc_context({'keymap.grid': sentinel})):
387387
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
388388

389389

@@ -397,8 +397,8 @@ def trigger(self, sender, event, data=None):
397397
sentinel = str(uuid.uuid4())
398398
# Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
399399
# to a unique key and sending an appropriate event.
400-
with cbook._setattr_cm(event, key=sentinel), \
401-
mpl.rc_context({'keymap.grid_minor': sentinel}):
400+
with (cbook._setattr_cm(event, key=sentinel),
401+
mpl.rc_context({'keymap.grid_minor': sentinel})):
402402
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
403403

404404

lib/matplotlib/backends/backend_pgf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -849,8 +849,8 @@ def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):
849849
cbook._check_and_log_subprocess(
850850
[texcommand, "-interaction=nonstopmode", "-halt-on-error",
851851
"figure.tex"], _log, cwd=tmpdir)
852-
with (tmppath / "figure.pdf").open("rb") as orig, \
853-
cbook.open_file_cm(fname_or_fh, "wb") as dest:
852+
with ((tmppath / "figure.pdf").open("rb") as orig,
853+
cbook.open_file_cm(fname_or_fh, "wb") as dest):
854854
shutil.copyfileobj(orig, dest) # copy file contents to target
855855

856856
def print_png(self, fname_or_fh, **kwargs):
@@ -862,8 +862,8 @@ def print_png(self, fname_or_fh, **kwargs):
862862
png_path = tmppath / "figure.png"
863863
self.print_pdf(pdf_path, **kwargs)
864864
converter(pdf_path, png_path, dpi=self.figure.dpi)
865-
with png_path.open("rb") as orig, \
866-
cbook.open_file_cm(fname_or_fh, "wb") as dest:
865+
with (png_path.open("rb") as orig,
866+
cbook.open_file_cm(fname_or_fh, "wb") as dest):
867867
shutil.copyfileobj(orig, dest) # copy file contents to target
868868

869869
def get_renderer(self):

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_svg.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1347,8 +1347,8 @@ def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):
13471347
renderer.finalize()
13481348

13491349
def print_svgz(self, filename, **kwargs):
1350-
with cbook.open_file_cm(filename, "wb") as fh, \
1351-
gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter:
1350+
with (cbook.open_file_cm(filename, "wb") as fh,
1351+
gzip.GzipFile(mode='w', fileobj=fh) as gzipwriter):
13521352
return self.print_svg(gzipwriter, **kwargs)
13531353

13541354
def get_default_filetype(self):

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/colorbar.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1115,10 +1115,8 @@ def _mesh(self):
11151115
# Update the norm values in a context manager as it is only
11161116
# a temporary change and we don't want to propagate any signals
11171117
# attached to the norm (callbacks.blocked).
1118-
with self.norm.callbacks.blocked(), \
1119-
cbook._setattr_cm(self.norm,
1120-
vmin=self.vmin,
1121-
vmax=self.vmax):
1118+
with (self.norm.callbacks.blocked(),
1119+
cbook._setattr_cm(self.norm, vmin=self.vmin, vmax=self.vmax)):
11221120
y = self.norm.inverse(y)
11231121
self._y = y
11241122
X, Y = np.meshgrid([0., 1.], y)

lib/matplotlib/figure.pyi

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from collections.abc import Callable, Hashable, Iterable
1+
from collections.abc import Callable, Hashable, Iterable, Sequence
22
import os
3-
from typing import Any, IO, Literal, Sequence, TypeVar, overload
3+
from typing import Any, IO, Literal, TypeVar, overload
44

55
import numpy as np
66
from numpy.typing import ArrayLike

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_api.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from __future__ import annotations
22

3+
from collections.abc import Callable
34
import re
45
import typing
5-
from typing import Any, Callable, TypeVar
6+
from typing import Any, TypeVar
67

78
import numpy as np
89
import pytest

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_backend_pdf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,8 @@ def test_multipage_keep_empty(tmp_path):
9191

9292
# an empty pdf is left behind with keep_empty=True
9393
fn = tmp_path / "b.pdf"
94-
with pytest.warns(mpl.MatplotlibDeprecationWarning), \
95-
PdfPages(fn, keep_empty=True) as pdf:
94+
with (pytest.warns(mpl.MatplotlibDeprecationWarning),
95+
PdfPages(fn, keep_empty=True) as pdf):
9696
pass
9797
assert fn.exists()
9898

@@ -112,8 +112,8 @@ def test_multipage_keep_empty(tmp_path):
112112

113113
# a non-empty pdf is left behind with keep_empty=True
114114
fn = tmp_path / "e.pdf"
115-
with pytest.warns(mpl.MatplotlibDeprecationWarning), \
116-
PdfPages(fn, keep_empty=True) as pdf:
115+
with (pytest.warns(mpl.MatplotlibDeprecationWarning),
116+
PdfPages(fn, keep_empty=True) as pdf):
117117
pdf.savefig(plt.figure())
118118
assert fn.exists()
119119

0 commit comments

Comments
 (0)