Skip to content

Py3fy cbook, compare_backend_driver_results #10955

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 1 commit into from
Apr 4, 2018
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
6 changes: 3 additions & 3 deletions lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -2574,13 +2574,13 @@ def _get_uniform_gridstate(ticks):
# keys in list 'all' enables all axes (default key 'a'),
# otherwise if key is a number only enable this particular axes
# if it was the axes, where the event was raised
if not (event.key in all_keys):
if event.key not in all_keys:
n = int(event.key) - 1
for i, a in enumerate(canvas.figure.get_axes()):
# consider axes, in which the event was raised
# FIXME: Why only this axes?
if event.x is not None and event.y is not None \
and a.in_axes(event):
if (event.x is not None and event.y is not None
and a.in_axes(event)):
if event.key in all_keys:
a.set_navigate(True)
else:
Expand Down
90 changes: 29 additions & 61 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
it imports matplotlib only at runtime.
"""

import six
from six.moves import xrange, zip
import collections
import contextlib
import datetime
Expand Down Expand Up @@ -57,9 +55,9 @@ def unicode_safe(s):
preferredencoding = None

if preferredencoding is None:
return six.text_type(s)
return str(s)
else:
return six.text_type(s, preferredencoding)
return str(s, preferredencoding)
return s


Expand All @@ -81,18 +79,11 @@ def __init__(self, cb):
self._destroy_callbacks = []
try:
try:
if six.PY3:
self.inst = ref(cb.__self__, self._destroy)
else:
self.inst = ref(cb.im_self, self._destroy)
self.inst = ref(cb.__self__, self._destroy)
except TypeError:
self.inst = None
if six.PY3:
self.func = cb.__func__
self.klass = cb.__self__.__class__
else:
self.func = cb.im_func
self.klass = cb.im_class
self.func = cb.__func__
self.klass = cb.__self__.__class__
except AttributeError:
self.inst = None
self.func = cb
Expand Down Expand Up @@ -158,12 +149,6 @@ def __eq__(self, other):
except Exception:
return False

def __ne__(self, other):
"""
Inverse of __eq__.
"""
return not self.__eq__(other)

def __hash__(self):
return self._hash

Expand Down Expand Up @@ -267,7 +252,7 @@ def connect(self, s, func):
return cid

def _remove_proxy(self, proxy):
for signal, proxies in list(six.iteritems(self._func_cid_map)):
for signal, proxies in list(self._func_cid_map.items()):
try:
del self.callbacks[signal][proxies[proxy]]
except KeyError:
Expand All @@ -280,15 +265,14 @@ def _remove_proxy(self, proxy):
def disconnect(self, cid):
"""Disconnect the callback registered with callback id *cid*.
"""
for eventname, callbackd in list(six.iteritems(self.callbacks)):
for eventname, callbackd in list(self.callbacks.items()):
try:
del callbackd[cid]
except KeyError:
continue
else:
for signal, functions in list(
six.iteritems(self._func_cid_map)):
for function, value in list(six.iteritems(functions)):
for signal, functions in list(self._func_cid_map.items()):
for function, value in list(functions.items()):
if value == cid:
del functions[function]
return
Expand All @@ -301,7 +285,7 @@ def process(self, s, *args, **kwargs):
called with ``*args`` and ``**kwargs``.
"""
if s in self.callbacks:
for cid, proxy in list(six.iteritems(self.callbacks[s])):
for cid, proxy in list(self.callbacks[s].items()):
try:
proxy(*args, **kwargs)
except ReferenceError:
Expand Down Expand Up @@ -471,7 +455,7 @@ def to_filehandle(fname, flag='rU', return_opened=False, encoding=None):
return to_filehandle(
os.fspath(fname),
flag=flag, return_opened=return_opened, encoding=encoding)
if isinstance(fname, six.string_types):
if isinstance(fname, str):
if fname.endswith('.gz'):
# get rid of 'U' in flag for gzipped files.
flag = flag.replace('U', '')
Expand Down Expand Up @@ -509,12 +493,12 @@ def open_file_cm(path_or_file, mode="r", encoding=None):

def is_scalar_or_string(val):
"""Return whether the given object is a scalar or string like."""
return isinstance(val, six.string_types) or not iterable(val)
return isinstance(val, str) or not iterable(val)


def _string_to_bool(s):
"""Parses the string argument as a boolean"""
if not isinstance(s, six.string_types):
if not isinstance(s, str):
return bool(s)
warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' as a "
"boolean is deprecated; use an actual boolean "
Expand Down Expand Up @@ -593,14 +577,7 @@ def mkdirs(newdir, mode=0o777):
"""
# this functionality is now in core python as of 3.2
# LPY DROP
if six.PY3:
os.makedirs(newdir, mode=mode, exist_ok=True)
else:
try:
os.makedirs(newdir, mode=mode)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
os.makedirs(newdir, mode=mode, exist_ok=True)


@deprecated('3.0')
Expand Down Expand Up @@ -921,7 +898,7 @@ def print_path(path):

outstream.write(" %s -- " % type(step))
if isinstance(step, dict):
for key, val in six.iteritems(step):
for key, val in step.items():
if val is next:
outstream.write("[{!r}]".format(key))
break
Expand Down Expand Up @@ -1072,13 +1049,13 @@ def __iter__(self):

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

# Cleanup the tokens
for group in six.itervalues(self._mapping):
for group in self._mapping.values():
if group[-1] is token:
del group[-1]

Expand Down Expand Up @@ -1149,14 +1126,13 @@ def delete_masked_points(*args):
"""
if not len(args):
return ()
if (isinstance(args[0], six.string_types) or not iterable(args[0])):
if isinstance(args[0], str) or not iterable(args[0]):
raise ValueError("First argument must be a sequence")
nrecs = len(args[0])
margs = []
seqlist = [False] * len(args)
for i, x in enumerate(args):
if (not isinstance(x, six.string_types) and iterable(x)
and len(x) == nrecs):
if not isinstance(x, str) and iterable(x) and len(x) == nrecs:
seqlist[i] = True
if isinstance(x, np.ma.MaskedArray):
if x.ndim > 1:
Expand Down Expand Up @@ -1313,7 +1289,7 @@ def _compute_conf_interval(data, med, iqr, bootstrap):
raise ValueError("Dimensions of labels and X must be compatible")

input_whis = whis
for ii, (x, label) in enumerate(zip(X, labels), start=0):
for ii, (x, label) in enumerate(zip(X, labels)):

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


@deprecated('2.2')
Expand Down Expand Up @@ -1480,16 +1456,9 @@ def contiguous_regions(mask):
def is_math_text(s):
# Did we find an even number of non-escaped dollar signs?
# If so, treat is as math text.
try:
s = six.text_type(s)
except UnicodeDecodeError:
raise ValueError(
"matplotlib display text must have all code points < 128 or use "
"Unicode strings")

s = str(s)
dollar_count = s.count(r'$') - s.count(r'\$')
even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)

return even_dollars


Expand Down Expand Up @@ -1833,7 +1802,7 @@ def normalize_kwargs(kw, alias_mapping=None, required=(), forbidden=(),
ret = dict()

# hit all alias mappings
for canonical, alias_list in six.iteritems(alias_mapping):
for canonical, alias_list in alias_mapping.items():

# the alias lists are ordered from lowest to highest priority
# so we know to use the last value in this list
Expand Down Expand Up @@ -1879,11 +1848,10 @@ def normalize_kwargs(kw, alias_mapping=None, required=(), forbidden=(),
allowed_set = set(required) | set(allowed)
fail_keys = [k for k in ret if k not in allowed_set]
if fail_keys:
raise TypeError("kwargs contains {keys!r} which are not in "
"the required {req!r} or "
"allowed {allow!r} keys".format(
keys=fail_keys, req=required,
allow=allowed))
raise TypeError(
"kwargs contains {keys!r} which are not in the required "
"{req!r} or allowed {allow!r} keys".format(
keys=fail_keys, req=required, allow=allowed))

return ret

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


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


def _define_aliases(alias_d, cls=None):
Expand Down
3 changes: 0 additions & 3 deletions lib/matplotlib/font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -661,9 +661,6 @@ def __hash__(self):
def __eq__(self, other):
return hash(self) == hash(other)

def __ne__(self, other):
return hash(self) != hash(other)

def __str__(self):
return self.get_fontconfig_pattern()

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _backend_selection():
if not rcParams['backend_fallback'] or backend not in _interactive_bk:
return
is_agg_backend = rcParams['backend'].endswith('Agg')
if 'wx' in sys.modules and not backend in ('WX', 'WXAgg'):
if 'wx' in sys.modules and backend not in ('WX', 'WXAgg'):
import wx
if wx.App.IsMainLoopRunning():
rcParams['backend'] = 'wx' + 'Agg' * is_agg_backend
Expand Down
37 changes: 18 additions & 19 deletions unit/compare_backend_driver_results.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
from __future__ import print_function
import sys


def parse_results(filename):
results = {}
fd = open(filename, 'r')
section = "???"
for line in fd.readlines():
line = line.strip()
if line.startswith("testing"):
section = line.split(" ", 1)[1]
results.setdefault(section, {})
elif line.startswith("driving"):
driving, test, time = [x.strip() for x in line.split()]
time = float(time)
results[section][test] = time
fd.close()
with open(filename, 'r') as file:
for line in file:
line = line.strip()
if line.startswith("testing"):
section = line.split(" ", 1)[1]
results.setdefault(section, {})
elif line.startswith("driving"):
driving, test, time = [x.strip() for x in line.split()]
time = float(time)
results[section][test] = time
return results


def check_results_are_compatible(results_a, results_b):
for section in results_a.keys():
if not section in results_b:
raise RuntimeError("Backend '%s' in first set, but not in second" % section)

for section in results_b.keys():
if not section in results_a:
raise RuntimeError("Backend '%s' in second set, but not in first" % section)
a_minus_b = {*results_a} - {*results_b}
if a_minus_b:
raise RuntimeError(
"Backends {} in first set, but not in second".format(a_minus_b))
b_minus_a = {*results_b} - {*results_a}
if b_minus_a:
raise RuntimeError(
"Backends {} in second set, but not in first".format(b_minus_a))


def compare_results(results_a, results_b):
Expand Down