Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 6a9a071

Browse filesBrowse files
authored
Merge pull request matplotlib#24980 from greglucas/py39-upgrade
Python 3.9 upgrade
2 parents 2403d74 + 63a8ad4 commit 6a9a071
Copy full SHA for 6a9a071

File tree

Expand file treeCollapse file tree

110 files changed

+324
-343
lines changed
Filter options

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Dismiss banner
Expand file treeCollapse file tree

110 files changed

+324
-343
lines changed

‎.git-blame-ignore-revs

Copy file name to clipboardExpand all lines: .git-blame-ignore-revs
+3Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,6 @@ c1a33a481b9c2df605bcb9bef9c19fe65c3dac21
99

1010
# chore: fix spelling errors
1111
686c9e5a413e31c46bb049407d5eca285bcab76d
12+
13+
# chore: pyupgrade --py39-plus
14+
4d306402bb66d6d4c694d8e3e14b91054417070e

‎doc/conf.py

Copy file name to clipboardExpand all lines: doc/conf.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ def _check_dependencies():
141141
if missing:
142142
raise ImportError(
143143
"The following dependencies are missing to build the "
144-
"documentation: {}".format(", ".join(missing)))
144+
f"documentation: {', '.join(missing)}")
145145
if shutil.which('dot') is None:
146146
raise OSError(
147147
"No binary named dot - graphviz must be installed to build the "

‎doc/sphinxext/gallery_order.py

Copy file name to clipboardExpand all lines: doc/sphinxext/gallery_order.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def __init__(self, src_dir):
114114
def __call__(self, item):
115115
"""Return a string determining the sort order."""
116116
if item in self.ordered_list:
117-
return "{:04d}".format(self.ordered_list.index(item))
117+
return f"{self.ordered_list.index(item):04d}"
118118
else:
119119
# ensure not explicitly listed items come last.
120120
return "zzz" + item

‎doc/sphinxext/missing_references.py

Copy file name to clipboardExpand all lines: doc/sphinxext/missing_references.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ def record_missing_reference(app, record, node):
6161
target = node["reftarget"]
6262
location = get_location(node, app)
6363

64-
domain_type = "{}:{}".format(domain, typ)
64+
domain_type = f"{domain}:{typ}"
6565

6666
record[(domain_type, target)].add(location)
6767

‎examples/color/color_cycle_default.py

Copy file name to clipboardExpand all lines: examples/color/color_cycle_default.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131
axs[1, icol].set_facecolor('k')
3232
axs[1, icol].xaxis.set_ticks(np.arange(0, 10, 2))
33-
axs[0, icol].set_title('line widths (pts): %g, %g' % (lwx, lwy),
33+
axs[0, icol].set_title(f'line widths (pts): {lwx:g}, {lwy:g}',
3434
fontsize='medium')
3535

3636
for irow in range(2):

‎examples/event_handling/cursor_demo.py

Copy file name to clipboardExpand all lines: examples/event_handling/cursor_demo.py
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def on_mouse_move(self, event):
5858
# update the line positions
5959
self.horizontal_line.set_ydata(y)
6060
self.vertical_line.set_xdata(x)
61-
self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))
61+
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
6262
self.ax.figure.canvas.draw()
6363

6464

@@ -134,7 +134,7 @@ def on_mouse_move(self, event):
134134
x, y = event.xdata, event.ydata
135135
self.horizontal_line.set_ydata(y)
136136
self.vertical_line.set_xdata(x)
137-
self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))
137+
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
138138

139139
self.ax.figure.canvas.restore_region(self.background)
140140
self.ax.draw_artist(self.horizontal_line)
@@ -206,7 +206,7 @@ def on_mouse_move(self, event):
206206
# update the line positions
207207
self.horizontal_line.set_ydata(y)
208208
self.vertical_line.set_xdata(x)
209-
self.text.set_text('x=%1.2f, y=%1.2f' % (x, y))
209+
self.text.set_text(f'x={x:1.2f}, y={y:1.2f}')
210210
self.ax.figure.canvas.draw()
211211

212212

‎examples/event_handling/pick_event_demo2.py

Copy file name to clipboardExpand all lines: examples/event_handling/pick_event_demo2.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def onpick(event):
4343
figi, axs = plt.subplots(N, squeeze=False)
4444
for ax, dataind in zip(axs.flat, event.ind):
4545
ax.plot(X[dataind])
46-
ax.text(.05, .9, 'mu=%1.3f\nsigma=%1.3f' % (xs[dataind], ys[dataind]),
46+
ax.text(.05, .9, f'mu={xs[dataind]:1.3f}\nsigma={ys[dataind]:1.3f}',
4747
transform=ax.transAxes, va='top')
4848
ax.set_ylim(-0.5, 1.5)
4949
figi.show()

‎examples/lines_bars_and_markers/bar_label_demo.py

Copy file name to clipboardExpand all lines: examples/lines_bars_and_markers/bar_label_demo.py
+2-4Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@
8080
ax.set_title('How fast do you want to go today?')
8181

8282
# Label with given captions, custom padding and annotate options
83-
ax.bar_label(hbars, labels=['±%.2f' % e for e in error],
83+
ax.bar_label(hbars, labels=[f'±{e:.2f}' for e in error],
8484
padding=8, color='b', fontsize=14)
8585
ax.set_xlim(right=16)
8686

@@ -106,9 +106,7 @@
106106
fig, ax = plt.subplots()
107107
bar_container = ax.bar(animal_names, mph_speed)
108108
ax.set(ylabel='speed in MPH', title='Running speeds', ylim=(0, 80))
109-
ax.bar_label(
110-
bar_container, fmt=lambda x: '{:.1f} km/h'.format(x * 1.61)
111-
)
109+
ax.bar_label(bar_container, fmt=lambda x: f'{x * 1.61:.1f} km/h')
112110

113111
# %%
114112
#

‎examples/scales/symlog_demo.py

Copy file name to clipboardExpand all lines: examples/scales/symlog_demo.py
-1Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
"""
32
===========
43
Symlog Demo

‎examples/shapes_and_collections/donut.py

Copy file name to clipboardExpand all lines: examples/shapes_and_collections/donut.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def make_circle(r):
5353
patch = mpatches.PathPatch(path, facecolor='#885500', edgecolor='black')
5454
ax.add_patch(patch)
5555

56-
ax.annotate("Outside %s,\nInside %s" % (wise(outside), wise(inside)),
56+
ax.annotate(f"Outside {wise(outside)},\nInside {wise(inside)}",
5757
(i * 2.5, -1.5), va="top", ha="center")
5858

5959
ax.set_xlim(-2, 10)

‎examples/user_interfaces/toolmanager_sgskip.py

Copy file name to clipboardExpand all lines: examples/user_interfaces/toolmanager_sgskip.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def trigger(self, *args, **kwargs):
3737
keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name)))
3838
print(fmt_tool(name, tools[name].description, keys))
3939
print('_' * 80)
40-
fmt_active_toggle = "{0!s:12} {1!s:45}".format
40+
fmt_active_toggle = "{!s:12} {!s:45}".format
4141
print("Active Toggle tools")
4242
print(fmt_active_toggle("Group", "Active"))
4343
print('-' * 80)

‎lib/matplotlib/__init__.py

Copy file name to clipboardExpand all lines: lib/matplotlib/__init__.py
+11-11Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ def _check_versions():
231231

232232
# The decorator ensures this always returns the same handler (and it is only
233233
# attached once).
234-
@functools.lru_cache()
234+
@functools.cache
235235
def _ensure_handler():
236236
"""
237237
The first time this function is called, attach a `StreamHandler` using the
@@ -321,7 +321,7 @@ class ExecutableNotFoundError(FileNotFoundError):
321321
pass
322322

323323

324-
@functools.lru_cache()
324+
@functools.cache
325325
def _get_executable_info(name):
326326
"""
327327
Get the version of some executable that Matplotlib optionally depends on.
@@ -364,7 +364,7 @@ def impl(args, regex, min_ver=None, ignore_exit_code=False):
364364
try:
365365
output = subprocess.check_output(
366366
args, stderr=subprocess.STDOUT,
367-
universal_newlines=True, errors="replace")
367+
text=True, errors="replace")
368368
except subprocess.CalledProcessError as _cpe:
369369
if ignore_exit_code:
370370
output = _cpe.output
@@ -459,7 +459,7 @@ def impl(args, regex, min_ver=None, ignore_exit_code=False):
459459
f"version supported by Matplotlib is 3.0")
460460
return info
461461
else:
462-
raise ValueError("Unknown executable: {!r}".format(name))
462+
raise ValueError(f"Unknown executable: {name!r}")
463463

464464

465465
@_api.deprecated("3.6", alternative="a vendored copy of this function")
@@ -757,7 +757,7 @@ def __repr__(self):
757757
repr_split = pprint.pformat(dict(self), indent=1,
758758
width=80 - indent).split('\n')
759759
repr_indented = ('\n' + ' ' * indent).join(repr_split)
760-
return '{}({})'.format(class_name, repr_indented)
760+
return f'{class_name}({repr_indented})'
761761

762762
def __str__(self):
763763
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
@@ -799,7 +799,7 @@ def rc_params(fail_on_error=False):
799799
return rc_params_from_file(matplotlib_fname(), fail_on_error)
800800

801801

802-
@functools.lru_cache()
802+
@functools.cache
803803
def _get_ssl_context():
804804
try:
805805
import certifi
@@ -1041,7 +1041,7 @@ def rc(group, **kwargs):
10411041
for g in group:
10421042
for k, v in kwargs.items():
10431043
name = aliases.get(k) or k
1044-
key = '%s.%s' % (g, name)
1044+
key = f'{g}.{name}'
10451045
try:
10461046
rcParams[key] = v
10471047
except KeyError as err:
@@ -1430,11 +1430,11 @@ def func(foo, label=None): ...
14301430
arg_names = arg_names[1:] # remove the first "ax" / self arg
14311431

14321432
assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
1433-
"Matplotlib internal error: invalid replace_names ({!r}) for {!r}"
1434-
.format(replace_names, func.__name__))
1433+
"Matplotlib internal error: invalid replace_names "
1434+
f"({replace_names!r}) for {func.__name__!r}")
14351435
assert label_namer is None or label_namer in arg_names, (
1436-
"Matplotlib internal error: invalid label_namer ({!r}) for {!r}"
1437-
.format(label_namer, func.__name__))
1436+
"Matplotlib internal error: invalid label_namer "
1437+
f"({label_namer!r}) for {func.__name__!r}")
14381438

14391439
@functools.wraps(func)
14401440
def inner(ax, *args, data=None, **kwargs):

‎lib/matplotlib/_api/__init__.py

Copy file name to clipboardExpand all lines: lib/matplotlib/_api/__init__.py
+9-9Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,10 @@ def check_shape(_shape, **kwargs):
158158
dim_labels = iter(itertools.chain(
159159
'MNLIJKLH',
160160
(f"D{i}" for i in itertools.count())))
161-
text_shape = ", ".join((str(n)
162-
if n is not None
163-
else next(dim_labels)
164-
for n in target_shape))
161+
text_shape = ", ".join(str(n)
162+
if n is not None
163+
else next(dim_labels)
164+
for n in target_shape)
165165
if len(target_shape) == 1:
166166
text_shape += ","
167167

@@ -190,8 +190,8 @@ def check_getitem(_mapping, **kwargs):
190190
return mapping[v]
191191
except KeyError:
192192
raise ValueError(
193-
"{!r} is not a valid value for {}; supported values are {}"
194-
.format(v, k, ', '.join(map(repr, mapping)))) from None
193+
f"{v!r} is not a valid value for {k}; supported values are "
194+
f"{', '.join(map(repr, mapping))}") from None
195195

196196

197197
def caching_module_getattr(cls):
@@ -219,7 +219,7 @@ def name(self): ...
219219
if isinstance(prop, property)}
220220
instance = cls()
221221

222-
@functools.lru_cache(None)
222+
@functools.cache
223223
def __getattr__(name):
224224
if name in props:
225225
return props[name].__get__(instance)
@@ -264,11 +264,11 @@ def method(self, *args, **kwargs):
264264
for alias in aliases:
265265
method = make_alias(prefix + prop)
266266
method.__name__ = prefix + alias
267-
method.__doc__ = "Alias for `{}`.".format(prefix + prop)
267+
method.__doc__ = f"Alias for `{prefix + prop}`."
268268
setattr(cls, prefix + alias, method)
269269
if not exists:
270270
raise ValueError(
271-
"Neither getter nor setter exists for {!r}".format(prop))
271+
f"Neither getter nor setter exists for {prop!r}")
272272

273273
def get_aliased_and_aliases(d):
274274
return {*d, *(alias for aliases in d.values() for alias in aliases)}

‎lib/matplotlib/_cm.py

Copy file name to clipboardExpand all lines: lib/matplotlib/_cm.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def _g34(x): return 2 * x
155155
def _g35(x): return 2 * x - 0.5
156156
def _g36(x): return 2 * x - 1
157157

158-
gfunc = {i: globals()["_g{}".format(i)] for i in range(37)}
158+
gfunc = {i: globals()[f"_g{i}"] for i in range(37)}
159159

160160
_gnuplot_data = {
161161
'red': gfunc[7],

‎lib/matplotlib/_fontconfig_pattern.py

Copy file name to clipboardExpand all lines: lib/matplotlib/_fontconfig_pattern.py
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,10 @@ def _make_fontconfig_parser():
5959
def comma_separated(elem):
6060
return elem + ZeroOrMore(Suppress(",") + elem)
6161

62-
family = Regex(r"([^%s]|(\\[%s]))*" % (_family_punc, _family_punc))
62+
family = Regex(fr"([^{_family_punc}]|(\\[{_family_punc}]))*")
6363
size = Regex(r"([0-9]+\.?[0-9]*|\.[0-9]+)")
6464
name = Regex(r"[a-z]+")
65-
value = Regex(r"([^%s]|(\\[%s]))*" % (_value_punc, _value_punc))
65+
value = Regex(fr"([^{_value_punc}]|(\\[{_value_punc}]))*")
6666
# replace trailing `| name` by oneOf(_CONSTANTS) in mpl 3.9.
6767
prop = Group((name + Suppress("=") + comma_separated(value)) | name)
6868
return (

‎lib/matplotlib/_mathtext.py

Copy file name to clipboardExpand all lines: lib/matplotlib/_mathtext.py
+9-9Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ def get_unicode_index(symbol, math=False): # Publicly exported.
6464
return tex2uni[symbol.strip("\\")]
6565
except KeyError as err:
6666
raise ValueError(
67-
"'{}' is not a valid Unicode character or TeX/Type1 symbol"
68-
.format(symbol)) from err
67+
f"{symbol!r} is not a valid Unicode character or TeX/Type1 symbol"
68+
) from err
6969

7070

7171
VectorParse = namedtuple("VectorParse", "width height depth glyphs rects",
@@ -273,7 +273,7 @@ class TruetypeFonts(Fonts):
273273
def __init__(self, *args, **kwargs):
274274
super().__init__(*args, **kwargs)
275275
# Per-instance cache.
276-
self._get_info = functools.lru_cache(None)(self._get_info)
276+
self._get_info = functools.cache(self._get_info)
277277
self._fonts = {}
278278

279279
filename = findfont(self.default_font_prop)
@@ -530,7 +530,7 @@ def _get_glyph(self, fontname, font_class, sym):
530530
except ValueError:
531531
uniindex = ord('?')
532532
found_symbol = False
533-
_log.warning("No TeX to Unicode mapping for {!a}.".format(sym))
533+
_log.warning(f"No TeX to Unicode mapping for {sym!a}.")
534534

535535
fontname, uniindex = self._map_virtual_font(
536536
fontname, font_class, uniindex)
@@ -576,9 +576,9 @@ def _get_glyph(self, fontname, font_class, sym):
576576
if (fontname in ('it', 'regular')
577577
and isinstance(self, StixFonts)):
578578
return self._get_glyph('rm', font_class, sym)
579-
_log.warning("Font {!r} does not have a glyph for {!a} "
580-
"[U+{:x}], substituting with a dummy "
581-
"symbol.".format(new_fontname, sym, uniindex))
579+
_log.warning(f"Font {new_fontname!r} does not have a glyph "
580+
f"for {sym!a} [U+{uniindex:x}], substituting "
581+
"with a dummy symbol.")
582582
font = self._get_font('rm')
583583
uniindex = 0xA4 # currency char, for lack of anything better
584584
slanted = False
@@ -752,7 +752,7 @@ def _map_virtual_font(self, fontname, font_class, uniindex):
752752

753753
return fontname, uniindex
754754

755-
@functools.lru_cache()
755+
@functools.cache
756756
def get_sized_alternatives_for_symbol(self, fontname, sym):
757757
fixes = {
758758
'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']',
@@ -1083,7 +1083,7 @@ def __init__(self, elements):
10831083
self.glue_order = 0 # The order of infinity (0 - 3) for the glue
10841084

10851085
def __repr__(self):
1086-
return '%s<w=%.02f h=%.02f d=%.02f s=%.02f>[%s]' % (
1086+
return '{}<w={:.02f} h={:.02f} d={:.02f} s={:.02f}>[{}]'.format(
10871087
super().__repr__(),
10881088
self.width, self.height,
10891089
self.depth, self.shift_amount,

‎lib/matplotlib/_type1font.py

Copy file name to clipboardExpand all lines: lib/matplotlib/_type1font.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ def _escape(cls, match):
140140
except KeyError:
141141
return chr(int(group, 8))
142142

143-
@functools.lru_cache()
143+
@functools.lru_cache
144144
def value(self):
145145
if self.raw[0] == '(':
146146
return self._escapes_re.sub(self._escape, self.raw[1:-1])

‎lib/matplotlib/animation.py

Copy file name to clipboardExpand all lines: lib/matplotlib/animation.py
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,7 @@ def output_args(self):
536536
args.extend(['-b', '%dk' % self.bitrate]) # %dk: bitrate in kbps.
537537
args.extend(extra_args)
538538
for k, v in self.metadata.items():
539-
args.extend(['-metadata', '%s=%s' % (k, v)])
539+
args.extend(['-metadata', f'{k}={v}'])
540540

541541
return args + ['-y', self.outfile]
542542

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.