Skip to content

Commit ff4560c

Browse files
committed
Fix a number of Deprecated/Invalid escape sequences
And turn python 3.6 DeprecationWarnings into error during tests. Python 3.6 deprecate invalid escape sequences, as they are (most of the time) mistakes from the author. This introduce extra `\` when necessary, or make strings `raw`. See #7924
1 parent eaf05e9 commit ff4560c

16 files changed

+67
-45
lines changed

lib/matplotlib/axes/_axes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6718,7 +6718,7 @@ def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,
67186718
Notes
67196719
-----
67206720
For plotting, the power is plotted as
6721-
:math:`10\log_{10}(P_{xy})` for decibels, though `P_{xy}` itself
6721+
:math:`10\\log_{10}(P_{xy})` for decibels, though `P_{xy}` itself
67226722
is returned.
67236723
67246724
References

lib/matplotlib/backends/backend_ps.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1568,7 +1568,7 @@ def xpdf_distill(tmpfile, eps=False, ptype='letter', bbox=None, rotated=False):
15681568
with io.open(outfile, 'rb') as fh:
15691569
if exit_status:
15701570
raise RuntimeError('ps2pdf was not able to process your \
1571-
image.\n\Here is the report generated by ghostscript:\n\n' + fh.read())
1571+
image.\nHere is the report generated by ghostscript:\n\n' + fh.read())
15721572
else:
15731573
verbose.report(fh.read(), 'debug')
15741574
os.remove(outfile)

lib/matplotlib/cbook/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -355,8 +355,8 @@ def disconnect(self, cid):
355355

356356
def process(self, s, *args, **kwargs):
357357
"""
358-
process signal *s*. All of the functions registered to receive
359-
callbacks on *s* will be called with *\*args* and *\*\*kwargs*
358+
process signal `s`. All of the functions registered to receive
359+
callbacks on `s` will be called with ``**args`` and ``**kwargs``
360360
"""
361361
if s in self.callbacks:
362362
for cid, proxy in list(six.iteritems(self.callbacks[s])):
@@ -944,7 +944,7 @@ def wrap(prefix, text, cols):
944944
# A regular expression used to determine the amount of space to
945945
# remove. It looks for the first sequence of spaces immediately
946946
# following the first newline, or at the beginning of the string.
947-
_find_dedent_regex = re.compile("(?:(?:\n\r?)|^)( *)\S")
947+
_find_dedent_regex = re.compile(r"(?:(?:\n\r?)|^)( *)\S")
948948
# A cache to hold the regexs that actually remove the indent.
949949
_dedent_regex = {}
950950

@@ -1722,7 +1722,7 @@ def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None,
17221722
17231723
.. math::
17241724
1725-
\mathrm{med} \pm 1.57 \\times \\frac{\mathrm{iqr}}{\sqrt{N}}
1725+
\\mathrm{med} \\pm 1.57 \\times \\frac{\\mathrm{iqr}}{\\sqrt{N}}
17261726
17271727
General approach from:
17281728
McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
@@ -2709,7 +2709,7 @@ def is_bounded_0_1(self):
27092709
def _get_key_params(self):
27102710
str_func = self._str_func
27112711
# Checking if it comes with parameters
2712-
regex = '\{(.*?)\}'
2712+
regex = r'\{(.*?)\}'
27132713
params = re.findall(regex, str_func)
27142714

27152715
for i, param in enumerate(params):

lib/matplotlib/collections.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,7 +394,7 @@ def set_hatch(self, hatch):
394394
*hatch* can be one of::
395395
396396
/ - diagonal hatching
397-
\ - back diagonal
397+
\\ - back diagonal
398398
| - vertical
399399
- - horizontal
400400
+ - crossed

lib/matplotlib/colors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ def to_hex(c, keep_alpha=False):
261261
### Backwards-compatible color-conversion API
262262

263263
cnames = CSS4_COLORS
264-
hexColorPattern = re.compile("\A#[a-fA-F0-9]{6}\Z")
264+
hexColorPattern = re.compile(r"\A#[a-fA-F0-9]{6}\Z")
265265

266266

267267
def rgb2hex(c):

lib/matplotlib/dviread.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,7 @@ def _height_depth_of(self, char):
587587

588588
class Vf(Dvi):
589589
"""
590-
A virtual font (\*.vf file) containing subroutines for dvi files.
590+
A virtual font (\\*.vf file) containing subroutines for dvi files.
591591
592592
Usage::
593593
@@ -899,7 +899,7 @@ def _register(self, words):
899899

900900
class Encoding(object):
901901
"""
902-
Parses a \*.enc file referenced from a psfonts.map style file.
902+
Parses a \\*.enc file referenced from a psfonts.map style file.
903903
The format this class understands is a very limited subset of
904904
PostScript.
905905

lib/matplotlib/font_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ def win32FontDirectory():
184184
Return the user-specified font directory for Win32. This is
185185
looked up from the registry key::
186186
187-
\\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
187+
\\\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Fonts
188188
189189
If the key is not found, $WINDIR/Fonts will be returned.
190190
"""

lib/matplotlib/mathtext.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def get_unicode_index(symbol, math=True):
6868
"""get_unicode_index(symbol, [bool]) -> integer
6969
7070
Return the integer index (from the Unicode table) of symbol. *symbol*
71-
can be a single unicode character, a TeX command (i.e. r'\pi'), or a
71+
can be a single unicode character, a TeX command (i.e. r'\\pi'), or a
7272
Type1 symbol name (i.e. 'phi').
7373
If math is False, the current symbol should be treated as a non-math symbol.
7474
"""
@@ -430,7 +430,7 @@ def get_kern(self, font1, fontclass1, sym1, fontsize1,
430430
431431
*fontclassX*: TODO
432432
433-
*symX*: a symbol in raw TeX form. e.g., '1', 'x' or '\sigma'
433+
*symX*: a symbol in raw TeX form. e.g., '1', 'x' or '\\sigma'
434434
435435
*fontsizeX*: the fontsize in points
436436
@@ -446,7 +446,7 @@ def get_metrics(self, font, font_class, sym, fontsize, dpi, math=True):
446446
447447
*font_class*: TODO
448448
449-
*sym*: a symbol in raw TeX form. e.g., '1', 'x' or '\sigma'
449+
*sym*: a symbol in raw TeX form. e.g., '1', 'x' or '\\sigma'
450450
451451
*fontsize*: font size in points
452452
@@ -749,12 +749,12 @@ def _get_glyph(self, fontname, font_class, sym, fontsize, math=True):
749749
r'>' : [('cal', 'i'), ('ex', 'E')]
750750
}
751751

752-
for alias, target in [('\leftparen', '('),
753-
('\rightparent', ')'),
754-
('\leftbrace', '{'),
755-
('\rightbrace', '}'),
756-
('\leftbracket', '['),
757-
('\rightbracket', ']'),
752+
for alias, target in [(r'\leftparen', '('),
753+
(r'\rightparent', ')'),
754+
(r'\leftbrace', '{'),
755+
(r'\rightbrace', '}'),
756+
(r'\leftbracket', '['),
757+
(r'\rightbracket', ']'),
758758
(r'\{', '{'),
759759
(r'\}', '}'),
760760
(r'\[', '['),
@@ -1034,7 +1034,7 @@ def _map_virtual_font(self, fontname, font_class, uniindex):
10341034

10351035
_size_alternatives = {}
10361036
def get_sized_alternatives_for_symbol(self, fontname, sym):
1037-
fixes = {'\{': '{', '\}': '}', '\[': '[', '\]': ']'}
1037+
fixes = {'\\{': '{', '\\}': '}', '\\[': '[', '\\]': ']'}
10381038
sym = fixes.get(sym, sym)
10391039

10401040
alternatives = self._size_alternatives.get(sym)
@@ -2425,20 +2425,20 @@ def __init__(self):
24252425
Suppress(Literal(r"\sqrt"))
24262426
- ((Optional(p.lbracket + p.int_literal + p.rbracket, default=None)
24272427
+ p.required_group)
2428-
| Error("Expected \sqrt{value}"))
2428+
| Error("Expected \\sqrt{value}"))
24292429
)
24302430

24312431
p.overline <<= Group(
24322432
Suppress(Literal(r"\overline"))
2433-
- (p.required_group | Error("Expected \overline{value}"))
2433+
- (p.required_group | Error("Expected \\overline{value}"))
24342434
)
24352435

24362436
p.unknown_symbol<<= Combine(p.bslash + Regex("[A-Za-z]*"))
24372437

24382438
p.operatorname <<= Group(
24392439
Suppress(Literal(r"\operatorname"))
24402440
- ((p.lbrace + ZeroOrMore(p.simple | p.unknown_symbol) + p.rbrace)
2441-
| Error("Expected \operatorname{value}"))
2441+
| Error("Expected \\operatorname{value}"))
24422442
)
24432443

24442444
p.placeable <<= ( p.snowflake # this needs to be before accent so named symbols
@@ -2693,7 +2693,7 @@ def unknown_symbol(self, s, loc, toks):
26932693
# The first 2 entires in the tuple are (font, char, sizescale) for
26942694
# the two symbols under and over. The third element is the space
26952695
# (in multiples of underline height)
2696-
r'AA' : ( ('it', 'A', 1.0), (None, '\circ', 0.5), 0.0),
2696+
r'AA': (('it', 'A', 1.0), (None, '\\circ', 0.5), 0.0),
26972697
}
26982698

26992699
def c_over_c(self, s, loc, toks):
@@ -2918,7 +2918,7 @@ def subsuper(self, s, loc, toks):
29182918
if super is None:
29192919
super = Hlist([])
29202920
for i in range(napostrophes):
2921-
super.children.extend(self.symbol(s, loc, ['\prime']))
2921+
super.children.extend(self.symbol(s, loc, ['\\prime']))
29222922
# kern() and hpack() needed to get the metrics right after extending
29232923
super.kern()
29242924
super.hpack()
@@ -3291,7 +3291,7 @@ def parse(self, s, dpi = 72, prop = None):
32913291
def to_mask(self, texstr, dpi=120, fontsize=14):
32923292
"""
32933293
*texstr*
3294-
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'
3294+
A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'
32953295
32963296
*dpi*
32973297
The dots-per-inch to render the text
@@ -3317,7 +3317,7 @@ def to_mask(self, texstr, dpi=120, fontsize=14):
33173317
def to_rgba(self, texstr, color='black', dpi=120, fontsize=14):
33183318
"""
33193319
*texstr*
3320-
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'
3320+
A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'
33213321
33223322
*color*
33233323
Any matplotlib color argument
@@ -3357,7 +3357,7 @@ def to_png(self, filename, texstr, color='black', dpi=120, fontsize=14):
33573357
A writable filename or fileobject
33583358
33593359
*texstr*
3360-
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'
3360+
A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'
33613361
33623362
*color*
33633363
A valid matplotlib color argument
@@ -3381,7 +3381,7 @@ def get_depth(self, texstr, dpi=120, fontsize=14):
33813381
image in pixels.
33823382
33833383
*texstr*
3384-
A valid mathtext string, e.g., r'IQ: $\sigma_i=15$'
3384+
A valid mathtext string, e.g., r'IQ: $\\sigma_i=15$'
33853385
33863386
*dpi*
33873387
The dots-per-inch to render the text

lib/matplotlib/mlab.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2191,7 +2191,7 @@ def identity(n, rank=2, dtype='l', typecode=None):
21912191
21922192
/ 1 if i0=i1=...=iR,
21932193
id[i0,i1,...,iR] = -|
2194-
\ 0 otherwise.
2194+
\\ 0 otherwise.
21952195
21962196
Optionally a *dtype* (or typecode) may be given (it defaults to 'l').
21972197
@@ -2869,7 +2869,7 @@ def get_converters(reader, comments):
28692869
break
28702870

28712871
# remove these chars
2872-
delete = set("""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")
2872+
delete = set(r"""~!@#$%^&*()-=+~\|]}[{';: /?.>,<""")
28732873
delete.add('"')
28742874

28752875
names = []

lib/matplotlib/patches.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ def set_hatch(self, hatch):
487487
*hatch* can be one of::
488488
489489
/ - diagonal hatching
490-
\ - back diagonal
490+
\\ - back diagonal
491491
| - vertical
492492
- - horizontal
493493
+ - crossed

lib/matplotlib/quiver.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,8 @@ def _h_arrows(self, length):
738738

739739
quiver_doc = _quiver_doc
740740

741-
_barbs_doc = """
741+
742+
_barbs_doc = r"""
742743
Plot a 2-D field of barbs.
743744
744745
Call signatures::

lib/matplotlib/tests/test_backend_svg.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,15 +149,14 @@ def _test_determinism_save(filename, usetex):
149149
a, b, c = ax.errorbar(x, y, yerr=yerr, fmt='ko')
150150
for artist in b:
151151
artist.set_visible(False)
152-
ax.set_title('A string $1+2+\sigma$')
153-
ax.set_xlabel('A string $1+2+\sigma$')
154-
ax.set_ylabel('A string $1+2+\sigma$')
152+
ax.set_title('A string $1+2+\\sigma$')
153+
ax.set_xlabel('A string $1+2+\\sigma$')
154+
ax.set_ylabel('A string $1+2+\\sigma$')
155155

156156
FigureCanvasSVG(fig).print_svg(filename)
157157

158158

159159
def _test_determinism(filename, usetex):
160-
import os
161160
import sys
162161
from subprocess import check_output, STDOUT, CalledProcessError
163162
plots = []

lib/matplotlib/tests/test_subplots.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def test_exceptions():
113113
# the point of this test is to ensure that this raises.
114114
with warnings.catch_warnings():
115115
warnings.filterwarnings('ignore',
116-
message='.*sharex\ argument\ to\ subplots',
116+
message='.*sharex argument to subplots',
117117
category=UserWarning)
118118
with pytest.raises(ValueError):
119119
plt.subplots(2, 2, -1)

lib/matplotlib/tests/test_text.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def find_matplotlib_font(**kw):
3030
from matplotlib.font_manager import FontProperties, findfont
3131
warnings.filterwarnings(
3232
'ignore',
33-
('findfont: Font family \[u?\'Foo\'\] not found. Falling back to .'),
33+
r'findfont: Font family \[u?\'Foo\'\] not found. Falling back to .',
3434
UserWarning,
3535
module='matplotlib.font_manager')
3636

@@ -135,7 +135,7 @@ def test_antialiasing():
135135
fig = plt.figure(figsize=(5.25, 0.75))
136136
fig.text(0.5, 0.75, "antialiased", horizontalalignment='center',
137137
verticalalignment='center')
138-
fig.text(0.5, 0.25, "$\sqrt{x}$", horizontalalignment='center',
138+
fig.text(0.5, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
139139
verticalalignment='center')
140140
# NOTE: We don't need to restore the rcParams here, because the
141141
# test cleanup will do it for us. In fact, if we do it here, it

lib/matplotlib/texmanager.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
Requirements:
88
99
* latex
10-
* \*Agg backends: dvipng
10+
* \\*Agg backends: dvipng
1111
* PS backend: latex w/ psfrag, dvips, and Ghostscript 8.51
1212
(older versions do not work properly)
1313
1414
Backends:
1515
16-
* \*Agg
16+
* \\*Agg
1717
* PS
1818
* PDF
1919
@@ -22,7 +22,7 @@
2222
2323
texmanager = TexManager()
2424
s = ('\\TeX\\ is Number '
25-
'$\\displaystyle\\sum_{n=1}^\\infty\\frac{-e^{i\pi}}{2^n}$!')
25+
'$\\displaystyle\\sum_{n=1}^\\infty\\frac{-e^{i\\pi}}{2^n}$!')
2626
Z = self.texmanager.get_rgba(s, size=12, dpi=80, rgb=(1,0,0))
2727
2828
To enable tex rendering of all text in your matplotlib figure, set

tests.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,28 @@
1414

1515

1616
if __name__ == '__main__':
17+
18+
try:
19+
import setuptools
20+
except ImportError:
21+
pass
22+
23+
# The warnings need to be before any of matplotlib imports, but after
24+
# setuptools (if present) which has syntax error with the warnings enabled.
25+
# Filtering by module does not work as this will be raised by Python itself.
26+
# so `module=matplotlib.*` is out of questions.
27+
28+
import warnings
29+
30+
# Python 3.6 deprecate invalid character-pairs \A, \* ... in non raw-strings
31+
# and other things. Let's not re-introduce them
32+
warnings.filterwarnings('error', '.*invalid escape sequence.*',
33+
category=DeprecationWarning)
34+
warnings.filterwarnings(
35+
'default',
36+
'.*inspect.getargspec\(\) is deprecated.*',
37+
category=DeprecationWarning)
38+
1739
from matplotlib import test
1840

1941
parser = argparse.ArgumentParser(add_help=False)

0 commit comments

Comments
 (0)