Skip to content

Commit dec87a3

Browse files
authored
Merge pull request #10955 from anntzer/py3cbook
Py3fy cbook, compare_backend_driver_results
2 parents b828756 + acae06d commit dec87a3

File tree

5 files changed

+51
-87
lines changed

5 files changed

+51
-87
lines changed

lib/matplotlib/backend_bases.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2574,13 +2574,13 @@ def _get_uniform_gridstate(ticks):
25742574
# keys in list 'all' enables all axes (default key 'a'),
25752575
# otherwise if key is a number only enable this particular axes
25762576
# if it was the axes, where the event was raised
2577-
if not (event.key in all_keys):
2577+
if event.key not in all_keys:
25782578
n = int(event.key) - 1
25792579
for i, a in enumerate(canvas.figure.get_axes()):
25802580
# consider axes, in which the event was raised
25812581
# FIXME: Why only this axes?
2582-
if event.x is not None and event.y is not None \
2583-
and a.in_axes(event):
2582+
if (event.x is not None and event.y is not None
2583+
and a.in_axes(event)):
25842584
if event.key in all_keys:
25852585
a.set_navigate(True)
25862586
else:

lib/matplotlib/cbook/__init__.py

Lines changed: 29 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
it imports matplotlib only at runtime.
77
"""
88

9-
import six
10-
from six.moves import xrange, zip
119
import collections
1210
import contextlib
1311
import datetime
@@ -57,9 +55,9 @@ def unicode_safe(s):
5755
preferredencoding = None
5856

5957
if preferredencoding is None:
60-
return six.text_type(s)
58+
return str(s)
6159
else:
62-
return six.text_type(s, preferredencoding)
60+
return str(s, preferredencoding)
6361
return s
6462

6563

@@ -81,18 +79,11 @@ def __init__(self, cb):
8179
self._destroy_callbacks = []
8280
try:
8381
try:
84-
if six.PY3:
85-
self.inst = ref(cb.__self__, self._destroy)
86-
else:
87-
self.inst = ref(cb.im_self, self._destroy)
82+
self.inst = ref(cb.__self__, self._destroy)
8883
except TypeError:
8984
self.inst = None
90-
if six.PY3:
91-
self.func = cb.__func__
92-
self.klass = cb.__self__.__class__
93-
else:
94-
self.func = cb.im_func
95-
self.klass = cb.im_class
85+
self.func = cb.__func__
86+
self.klass = cb.__self__.__class__
9687
except AttributeError:
9788
self.inst = None
9889
self.func = cb
@@ -158,12 +149,6 @@ def __eq__(self, other):
158149
except Exception:
159150
return False
160151

161-
def __ne__(self, other):
162-
"""
163-
Inverse of __eq__.
164-
"""
165-
return not self.__eq__(other)
166-
167152
def __hash__(self):
168153
return self._hash
169154

@@ -267,7 +252,7 @@ def connect(self, s, func):
267252
return cid
268253

269254
def _remove_proxy(self, proxy):
270-
for signal, proxies in list(six.iteritems(self._func_cid_map)):
255+
for signal, proxies in list(self._func_cid_map.items()):
271256
try:
272257
del self.callbacks[signal][proxies[proxy]]
273258
except KeyError:
@@ -280,15 +265,14 @@ def _remove_proxy(self, proxy):
280265
def disconnect(self, cid):
281266
"""Disconnect the callback registered with callback id *cid*.
282267
"""
283-
for eventname, callbackd in list(six.iteritems(self.callbacks)):
268+
for eventname, callbackd in list(self.callbacks.items()):
284269
try:
285270
del callbackd[cid]
286271
except KeyError:
287272
continue
288273
else:
289-
for signal, functions in list(
290-
six.iteritems(self._func_cid_map)):
291-
for function, value in list(six.iteritems(functions)):
274+
for signal, functions in list(self._func_cid_map.items()):
275+
for function, value in list(functions.items()):
292276
if value == cid:
293277
del functions[function]
294278
return
@@ -301,7 +285,7 @@ def process(self, s, *args, **kwargs):
301285
called with ``*args`` and ``**kwargs``.
302286
"""
303287
if s in self.callbacks:
304-
for cid, proxy in list(six.iteritems(self.callbacks[s])):
288+
for cid, proxy in list(self.callbacks[s].items()):
305289
try:
306290
proxy(*args, **kwargs)
307291
except ReferenceError:
@@ -471,7 +455,7 @@ def to_filehandle(fname, flag='rU', return_opened=False, encoding=None):
471455
return to_filehandle(
472456
os.fspath(fname),
473457
flag=flag, return_opened=return_opened, encoding=encoding)
474-
if isinstance(fname, six.string_types):
458+
if isinstance(fname, str):
475459
if fname.endswith('.gz'):
476460
# get rid of 'U' in flag for gzipped files.
477461
flag = flag.replace('U', '')
@@ -509,12 +493,12 @@ def open_file_cm(path_or_file, mode="r", encoding=None):
509493

510494
def is_scalar_or_string(val):
511495
"""Return whether the given object is a scalar or string like."""
512-
return isinstance(val, six.string_types) or not iterable(val)
496+
return isinstance(val, str) or not iterable(val)
513497

514498

515499
def _string_to_bool(s):
516500
"""Parses the string argument as a boolean"""
517-
if not isinstance(s, six.string_types):
501+
if not isinstance(s, str):
518502
return bool(s)
519503
warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' as a "
520504
"boolean is deprecated; use an actual boolean "
@@ -593,14 +577,7 @@ def mkdirs(newdir, mode=0o777):
593577
"""
594578
# this functionality is now in core python as of 3.2
595579
# LPY DROP
596-
if six.PY3:
597-
os.makedirs(newdir, mode=mode, exist_ok=True)
598-
else:
599-
try:
600-
os.makedirs(newdir, mode=mode)
601-
except OSError as exception:
602-
if exception.errno != errno.EEXIST:
603-
raise
580+
os.makedirs(newdir, mode=mode, exist_ok=True)
604581

605582

606583
@deprecated('3.0')
@@ -921,7 +898,7 @@ def print_path(path):
921898

922899
outstream.write(" %s -- " % type(step))
923900
if isinstance(step, dict):
924-
for key, val in six.iteritems(step):
901+
for key, val in step.items():
925902
if val is next:
926903
outstream.write("[{!r}]".format(key))
927904
break
@@ -1072,13 +1049,13 @@ def __iter__(self):
10721049

10731050
# Mark each group as we come across if by appending a token,
10741051
# and don't yield it twice
1075-
for group in six.itervalues(self._mapping):
1052+
for group in self._mapping.values():
10761053
if group[-1] is not token:
10771054
yield [x() for x in group]
10781055
group.append(token)
10791056

10801057
# Cleanup the tokens
1081-
for group in six.itervalues(self._mapping):
1058+
for group in self._mapping.values():
10821059
if group[-1] is token:
10831060
del group[-1]
10841061

@@ -1149,14 +1126,13 @@ def delete_masked_points(*args):
11491126
"""
11501127
if not len(args):
11511128
return ()
1152-
if (isinstance(args[0], six.string_types) or not iterable(args[0])):
1129+
if isinstance(args[0], str) or not iterable(args[0]):
11531130
raise ValueError("First argument must be a sequence")
11541131
nrecs = len(args[0])
11551132
margs = []
11561133
seqlist = [False] * len(args)
11571134
for i, x in enumerate(args):
1158-
if (not isinstance(x, six.string_types) and iterable(x)
1159-
and len(x) == nrecs):
1135+
if not isinstance(x, str) and iterable(x) and len(x) == nrecs:
11601136
seqlist[i] = True
11611137
if isinstance(x, np.ma.MaskedArray):
11621138
if x.ndim > 1:
@@ -1313,7 +1289,7 @@ def _compute_conf_interval(data, med, iqr, bootstrap):
13131289
raise ValueError("Dimensions of labels and X must be compatible")
13141290

13151291
input_whis = whis
1316-
for ii, (x, label) in enumerate(zip(X, labels), start=0):
1292+
for ii, (x, label) in enumerate(zip(X, labels)):
13171293

13181294
# empty dict
13191295
stats = {}
@@ -1403,7 +1379,7 @@ def _compute_conf_interval(data, med, iqr, bootstrap):
14031379
# The ls_mapper maps short codes for line style to their full name used by
14041380
# backends; the reverse mapper is for mapping full names to short ones.
14051381
ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
1406-
ls_mapper_r = {v: k for k, v in six.iteritems(ls_mapper)}
1382+
ls_mapper_r = {v: k for k, v in ls_mapper.items()}
14071383

14081384

14091385
@deprecated('2.2')
@@ -1480,16 +1456,9 @@ def contiguous_regions(mask):
14801456
def is_math_text(s):
14811457
# Did we find an even number of non-escaped dollar signs?
14821458
# If so, treat is as math text.
1483-
try:
1484-
s = six.text_type(s)
1485-
except UnicodeDecodeError:
1486-
raise ValueError(
1487-
"matplotlib display text must have all code points < 128 or use "
1488-
"Unicode strings")
1489-
1459+
s = str(s)
14901460
dollar_count = s.count(r'$') - s.count(r'\$')
14911461
even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
1492-
14931462
return even_dollars
14941463

14951464

@@ -1833,7 +1802,7 @@ def normalize_kwargs(kw, alias_mapping=None, required=(), forbidden=(),
18331802
ret = dict()
18341803

18351804
# hit all alias mappings
1836-
for canonical, alias_list in six.iteritems(alias_mapping):
1805+
for canonical, alias_list in alias_mapping.items():
18371806

18381807
# the alias lists are ordered from lowest to highest priority
18391808
# so we know to use the last value in this list
@@ -1879,11 +1848,10 @@ def normalize_kwargs(kw, alias_mapping=None, required=(), forbidden=(),
18791848
allowed_set = set(required) | set(allowed)
18801849
fail_keys = [k for k in ret if k not in allowed_set]
18811850
if fail_keys:
1882-
raise TypeError("kwargs contains {keys!r} which are not in "
1883-
"the required {req!r} or "
1884-
"allowed {allow!r} keys".format(
1885-
keys=fail_keys, req=required,
1886-
allow=allowed))
1851+
raise TypeError(
1852+
"kwargs contains {keys!r} which are not in the required "
1853+
"{req!r} or allowed {allow!r} keys".format(
1854+
keys=fail_keys, req=required, allow=allowed))
18871855

18881856
return ret
18891857

@@ -2014,7 +1982,7 @@ def _str_equal(obj, s):
20141982
because in such cases, a naive ``obj == s`` would yield an array, which
20151983
cannot be used in a boolean context.
20161984
"""
2017-
return isinstance(obj, six.string_types) and obj == s
1985+
return isinstance(obj, str) and obj == s
20181986

20191987

20201988
def _str_lower_equal(obj, s):
@@ -2024,7 +1992,7 @@ def _str_lower_equal(obj, s):
20241992
because in such cases, a naive ``obj == s`` would yield an array, which
20251993
cannot be used in a boolean context.
20261994
"""
2027-
return isinstance(obj, six.string_types) and obj.lower() == s
1995+
return isinstance(obj, str) and obj.lower() == s
20281996

20291997

20301998
def _define_aliases(alias_d, cls=None):

lib/matplotlib/font_manager.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -661,9 +661,6 @@ def __hash__(self):
661661
def __eq__(self, other):
662662
return hash(self) == hash(other)
663663

664-
def __ne__(self, other):
665-
return hash(self) != hash(other)
666-
667664
def __str__(self):
668665
return self.get_fontconfig_pattern()
669666

lib/matplotlib/pyplot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def _backend_selection():
7878
if not rcParams['backend_fallback'] or backend not in _interactive_bk:
7979
return
8080
is_agg_backend = rcParams['backend'].endswith('Agg')
81-
if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
81+
if 'wx' in sys.modules and backend not in ('WX', 'WXAgg'):
8282
import wx
8383
if wx.App.IsMainLoopRunning():
8484
rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend

unit/compare_backend_driver_results.py

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,31 @@
1-
from __future__ import print_function
21
import sys
32

43

54
def parse_results(filename):
65
results = {}
7-
fd = open(filename, 'r')
86
section = "???"
9-
for line in fd.readlines():
10-
line = line.strip()
11-
if line.startswith("testing"):
12-
section = line.split(" ", 1)[1]
13-
results.setdefault(section, {})
14-
elif line.startswith("driving"):
15-
driving, test, time = [x.strip() for x in line.split()]
16-
time = float(time)
17-
results[section][test] = time
18-
fd.close()
7+
with open(filename, 'r') as file:
8+
for line in file:
9+
line = line.strip()
10+
if line.startswith("testing"):
11+
section = line.split(" ", 1)[1]
12+
results.setdefault(section, {})
13+
elif line.startswith("driving"):
14+
driving, test, time = [x.strip() for x in line.split()]
15+
time = float(time)
16+
results[section][test] = time
1917
return results
2018

2119

2220
def check_results_are_compatible(results_a, results_b):
23-
for section in results_a.keys():
24-
if not section in results_b:
25-
raise RuntimeError("Backend '%s' in first set, but not in second" % section)
26-
27-
for section in results_b.keys():
28-
if not section in results_a:
29-
raise RuntimeError("Backend '%s' in second set, but not in first" % section)
21+
a_minus_b = {*results_a} - {*results_b}
22+
if a_minus_b:
23+
raise RuntimeError(
24+
"Backends {} in first set, but not in second".format(a_minus_b))
25+
b_minus_a = {*results_b} - {*results_a}
26+
if b_minus_a:
27+
raise RuntimeError(
28+
"Backends {} in second set, but not in first".format(b_minus_a))
3029

3130

3231
def compare_results(results_a, results_b):

0 commit comments

Comments
 (0)