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

Skip to content

Upgrade code to Python 3.10 #28599

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 7 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion galleries/examples/showcase/stock_prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
'ADBE', 'GSPC', 'IXIC']

# Manually adjust the label positions vertically (units are points = 1/72 inch)
y_offsets = {k: 0 for k in stocks_ticker}
y_offsets = dict.fromkeys(stocks_ticker, 0)
y_offsets['IBM'] = 5
y_offsets['AAPL'] = -5
y_offsets['AMZN'] = -6
Expand Down
3 changes: 2 additions & 1 deletion galleries/examples/units/basic_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

"""

import itertools
import math

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

class UnitResolver:
def addition_rule(self, units):
for unit_1, unit_2 in zip(units[:-1], units[1:]):
for unit_1, unit_2 in itertools.pairwise(units):
if unit_1 != unit_2:
return NotImplemented
return units[0]
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/_api/__init__.pyi
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from collections.abc import Callable, Generator, Mapping, Sequence
from typing import Any, Iterable, TypeVar, overload
from collections.abc import Callable, Generator, Iterable, Mapping, Sequence
from typing import Any, TypeVar, overload
from typing_extensions import Self # < Py 3.11

from numpy.typing import NDArray
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/_docstring.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ def __missing__(self, key):
name = key[:-len(":kwdoc")]
from matplotlib.artist import Artist, kwdoc
try:
cls, = [cls for cls in _api.recursive_subclasses(Artist)
if cls.__name__ == name]
cls, = (cls for cls in _api.recursive_subclasses(Artist)
if cls.__name__ == name)
except ValueError as e:
raise KeyError(key) from e
return self.setdefault(key, kwdoc(cls))
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/_docstring.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Callable, TypeVar, overload
from collections.abc import Callable
from typing import Any, TypeVar, overload


_T = TypeVar('_T')
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/_mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ def _get_info(self, fontname: str, font_class: str, sym: str, fontsize: float,
font.set_size(fontsize, dpi)
glyph = font.load_char(num, flags=self.load_glyph_flags)

xmin, ymin, xmax, ymax = [val/64.0 for val in glyph.bbox]
xmin, ymin, xmax, ymax = (val / 64 for val in glyph.bbox)
offset = self._get_offset(font, glyph, fontsize, dpi)
metrics = FontMetrics(
advance = glyph.linearHoriAdvance/65536.0,
Expand Down Expand Up @@ -2645,7 +2645,7 @@ def _genfrac(self, ldelim: str, rdelim: str, rule: float | None, style: _MathSty
if rdelim == '':
rdelim = '.'
return self._auto_sized_delimiter(ldelim,
T.cast(list[T.Union[Box, Char, str]],
T.cast(list[Box | Char | str],
result),
rdelim)
return result
Expand Down Expand Up @@ -2786,7 +2786,7 @@ def _auto_sized_delimiter(self, front: str,
del middle[idx]
# There should only be \middle and its delimiter as str, which have
# just been removed.
middle_part = T.cast(list[T.Union[Box, Char]], middle)
middle_part = T.cast(list[Box | Char], middle)
else:
height = 0
depth = 0
Expand Down
10 changes: 4 additions & 6 deletions lib/matplotlib/_mathtext_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""

from __future__ import annotations
from typing import overload, Union
from typing import overload

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

_EntryTypeIn = tuple[str, str, str, Union[str, int]]
_EntryTypeIn = tuple[str, str, str, str | int]
_EntryTypeOut = tuple[int, int, str, int]

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


stix_virtual_fonts: dict[str, Union[dict[str, list[_EntryTypeOut]],
list[_EntryTypeOut]]]
stix_virtual_fonts: dict[str, dict[str, list[_EntryTypeOut]] | list[_EntryTypeOut]]
stix_virtual_fonts = _normalize_stix_fontcodes(_stix_virtual_fonts)

# Free redundant list now that it has been normalized
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,8 +1086,8 @@ def _pre_composite_to_white(color):
# canvas._is_saving = True makes the draw_event animation-starting
# callback a no-op; canvas.manager = None prevents resizing the GUI
# widget (both are likewise done in savefig()).
with writer.saving(self._fig, filename, dpi), \
cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None):
with (writer.saving(self._fig, filename, dpi),
cbook._setattr_cm(self._fig.canvas, _is_saving=True, manager=None)):
for anim in all_anim:
anim._init_draw() # Clear the initial frame
frame_number = 0
Expand Down
6 changes: 4 additions & 2 deletions lib/matplotlib/artist.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from collections import namedtuple
import contextlib
from functools import cache, wraps
from functools import cache, reduce, wraps
import inspect
from inspect import Signature, Parameter
import logging
from numbers import Number, Real
import operator
import re
import warnings

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

artists = sum([c.findobj(matchfunc) for c in self.get_children()], [])
artists = reduce(operator.iadd,
[c.findobj(matchfunc) for c in self.get_children()], [])
if include_self and matchfunc(self):
artists.append(self)
return artists
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6000,7 +6000,7 @@ def _pcolorargs(self, funcname, *args, shading='auto', **kwargs):
# unit conversion allows e.g. datetime objects as axis values
X, Y = args[:2]
X, Y = self._process_unit_info([("x", X), ("y", Y)], kwargs)
X, Y = [cbook.safe_masked_invalid(a, copy=True) for a in [X, Y]]
X, Y = (cbook.safe_masked_invalid(a, copy=True) for a in [X, Y])

if funcname == 'pcolormesh':
if np.ma.is_masked(X) or np.ma.is_masked(Y):
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ def __init__(self, fig,
self._aspect = 'auto'
self._adjustable = 'box'
self._anchor = 'C'
self._stale_viewlims = {name: False for name in self._axis_names}
self._stale_viewlims = dict.fromkeys(self._axis_names, False)
self._forward_navigation_events = forward_navigation_events
self._sharex = sharex
self._sharey = sharey
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
# allows all Line2D kwargs.
_line_inspector = martist.ArtistInspector(mlines.Line2D)
_line_param_names = _line_inspector.get_setters()
_line_param_aliases = [list(d)[0] for d in _line_inspector.aliasd.values()]
_line_param_aliases = [next(iter(d)) for d in _line_inspector.aliasd.values()]
_gridline_param_names = ['grid_' + name
for name in _line_param_names + _line_param_aliases]

Expand Down Expand Up @@ -728,8 +728,8 @@ def _get_shared_axis(self):

def _get_axis_name(self):
"""Return the axis name."""
return [name for name, axis in self.axes._axis_map.items()
if axis is self][0]
return next(name for name, axis in self.axes._axis_map.items()
if axis is self)

# During initialization, Axis objects often create ticks that are later
# unused; this turns out to be a very slow step. Instead, use a custom
Expand Down
18 changes: 9 additions & 9 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1972,8 +1972,8 @@ def _switch_canvas_and_return_print_method(self, fmt, backend=None):
"""
Context manager temporarily setting the canvas for saving the figure::

with canvas._switch_canvas_and_return_print_method(fmt, backend) \\
as print_method:
with (canvas._switch_canvas_and_return_print_method(fmt, backend)
as print_method):
# ``print_method`` is a suitable ``print_{fmt}`` method, and
# the figure's canvas is temporarily switched to the method's
# canvas within the with... block. ``print_method`` is also
Expand Down Expand Up @@ -2110,13 +2110,13 @@ def print_figure(
"'figure', or omit the *papertype* argument entirely.")

# Remove the figure manager, if any, to avoid resizing the GUI widget.
with cbook._setattr_cm(self, manager=None), \
self._switch_canvas_and_return_print_method(format, backend) \
as print_method, \
cbook._setattr_cm(self.figure, dpi=dpi), \
cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1), \
cbook._setattr_cm(self.figure.canvas, _is_saving=True), \
ExitStack() as stack:
with (cbook._setattr_cm(self, manager=None),
self._switch_canvas_and_return_print_method(format, backend)
as print_method,
cbook._setattr_cm(self.figure, dpi=dpi),
cbook._setattr_cm(self.figure.canvas, _device_pixel_ratio=1),
cbook._setattr_cm(self.figure.canvas, _is_saving=True),
ExitStack() as stack):

for prop in ["facecolor", "edgecolor"]:
color = locals()[prop]
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backend_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,8 +382,8 @@ def trigger(self, sender, event, data=None):
sentinel = str(uuid.uuid4())
# Trigger grid switching by temporarily setting :rc:`keymap.grid`
# to a unique key and sending an appropriate event.
with cbook._setattr_cm(event, key=sentinel), \
mpl.rc_context({'keymap.grid': sentinel}):
with (cbook._setattr_cm(event, key=sentinel),
mpl.rc_context({'keymap.grid': sentinel})):
mpl.backend_bases.key_press_handler(event, self.figure.canvas)


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


Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/backends/backend_pgf.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,8 +849,8 @@ def print_pdf(self, fname_or_fh, *, metadata=None, **kwargs):
cbook._check_and_log_subprocess(
[texcommand, "-interaction=nonstopmode", "-halt-on-error",
"figure.tex"], _log, cwd=tmpdir)
with (tmppath / "figure.pdf").open("rb") as orig, \
cbook.open_file_cm(fname_or_fh, "wb") as dest:
with ((tmppath / "figure.pdf").open("rb") as orig,
cbook.open_file_cm(fname_or_fh, "wb") as dest):
shutil.copyfileobj(orig, dest) # copy file contents to target

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

def get_renderer(self):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_qt.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ def blit(self, bbox=None):
if bbox is None and self.figure:
bbox = self.figure.bbox # Blit the entire canvas if bbox is None.
# repaint uses logical pixels, not physical pixels like the renderer.
l, b, w, h = [int(pt / self.device_pixel_ratio) for pt in bbox.bounds]
l, b, w, h = (int(pt / self.device_pixel_ratio) for pt in bbox.bounds)
t = b + h
self.repaint(l, self.rect().height() - t, w, h)

Expand All @@ -504,7 +504,7 @@ def drawRectangle(self, rect):
# Draw the zoom rectangle to the QPainter. _draw_rect_callback needs
# to be called at the end of paintEvent.
if rect is not None:
x0, y0, w, h = [int(pt / self.device_pixel_ratio) for pt in rect]
x0, y0, w, h = (int(pt / self.device_pixel_ratio) for pt in rect)
x1 = x0 + w
y1 = y0 + h
def _draw_rect_callback(painter):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -1347,8 +1347,8 @@ def print_svg(self, filename, *, bbox_inches_restore=None, metadata=None):
renderer.finalize()

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

def get_default_filetype(self):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/backends/backend_wx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1197,8 +1197,8 @@ def _get_tool_pos(self, tool):
``ToolBar.GetToolPos`` is not useful because wx assigns the same Id to
all Separators and StretchableSpaces.
"""
pos, = [pos for pos in range(self.ToolsCount)
if self.GetToolByPos(pos) == tool]
pos, = (pos for pos in range(self.ToolsCount)
if self.GetToolByPos(pos) == tool)
return pos

def add_toolitem(self, name, group, position, image_file, description,
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/bezier.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def get_intersection(cx1, cy1, cos_t1, sin_t1,
# rhs_inverse
a_, b_ = d, -b
c_, d_ = -c, a
a_, b_, c_, d_ = [k / ad_bc for k in [a_, b_, c_, d_]]
a_, b_, c_, d_ = (k / ad_bc for k in [a_, b_, c_, d_])

x = a_ * line1_rhs + b_ * line2_rhs
y = c_ * line1_rhs + d_ * line2_rhs
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -1115,10 +1115,8 @@ def _mesh(self):
# Update the norm values in a context manager as it is only
# a temporary change and we don't want to propagate any signals
# attached to the norm (callbacks.blocked).
with self.norm.callbacks.blocked(), \
cbook._setattr_cm(self.norm,
vmin=self.vmin,
vmax=self.vmax):
with (self.norm.callbacks.blocked(),
cbook._setattr_cm(self.norm, vmin=self.vmin, vmax=self.vmax)):
y = self.norm.inverse(y)
self._y = y
X, Y = np.meshgrid([0., 1.], y)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/figure.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from collections.abc import Callable, Hashable, Iterable
from collections.abc import Callable, Hashable, Iterable, Sequence
import os
from typing import Any, IO, Literal, Sequence, TypeVar, overload
from typing import Any, IO, Literal, TypeVar, overload

import numpy as np
from numpy.typing import ArrayLike
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,13 +424,13 @@ def _parse_args(*args, caller_name='function'):
X = X.ravel()
Y = Y.ravel()
if len(X) == nc and len(Y) == nr:
X, Y = [a.ravel() for a in np.meshgrid(X, Y)]
X, Y = (a.ravel() for a in np.meshgrid(X, Y))
elif len(X) != len(Y):
raise ValueError('X and Y must be the same size, but '
f'X.size is {X.size} and Y.size is {Y.size}.')
else:
indexgrid = np.meshgrid(np.arange(nc), np.arange(nr))
X, Y = [np.ravel(a) for a in indexgrid]
X, Y = (np.ravel(a) for a in indexgrid)
# Size validation for U, V, C is left to the set_UVC method.
return X, Y, U, V, C

Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import annotations

from collections.abc import Callable
import re
import typing
from typing import Any, Callable, TypeVar
from typing import Any, TypeVar

import numpy as np
import pytest
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3086,10 +3086,10 @@ def test_log_scales():
ax.set_yscale('log', base=5.5)
ax.invert_yaxis()
ax.set_xscale('log', base=9.0)
xticks, yticks = [
xticks, yticks = (
[(t.get_loc(), t.label1.get_text()) for t in axis._update_ticks()]
for axis in [ax.xaxis, ax.yaxis]
]
)
assert xticks == [
(1.0, '$\\mathdefault{9^{0}}$'),
(9.0, '$\\mathdefault{9^{1}}$'),
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/tests/test_backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ def test_multipage_keep_empty(tmp_path):

# an empty pdf is left behind with keep_empty=True
fn = tmp_path / "b.pdf"
with pytest.warns(mpl.MatplotlibDeprecationWarning), \
PdfPages(fn, keep_empty=True) as pdf:
with (pytest.warns(mpl.MatplotlibDeprecationWarning),
PdfPages(fn, keep_empty=True) as pdf):
pass
assert fn.exists()

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

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

Expand Down
Loading
Loading