Skip to content

Commit de5a4ee

Browse files
committed
Cleanup some bare excepts and related code.
1 parent a8fe0b3 commit de5a4ee

File tree

17 files changed

+161
-109
lines changed

17 files changed

+161
-109
lines changed

lib/matplotlib/_backports/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
"""
2+
Backported features from dependencies.
3+
"""

lib/matplotlib/_backports/numpy.py

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
from __future__ import absolute_import
2+
3+
import numpy as np
4+
5+
6+
# Copy-pasted from numpy.lib.stride_tricks 1.11.2.
7+
def _maybe_view_as_subclass(original_array, new_array):
8+
if type(original_array) is not type(new_array):
9+
# if input was an ndarray subclass and subclasses were OK,
10+
# then view the result as that subclass.
11+
new_array = new_array.view(type=type(original_array))
12+
# Since we have done something akin to a view from original_array, we
13+
# should let the subclass finalize (if it has it implemented, i.e., is
14+
# not None).
15+
if new_array.__array_finalize__:
16+
new_array.__array_finalize__(original_array)
17+
return new_array
18+
19+
20+
# Copy-pasted from numpy.lib.stride_tricks 1.11.2.
21+
def _broadcast_to(array, shape, subok, readonly):
22+
shape = tuple(shape) if np.iterable(shape) else (shape,)
23+
array = np.array(array, copy=False, subok=subok)
24+
if not shape and array.shape:
25+
raise ValueError('cannot broadcast a non-scalar to a scalar array')
26+
if any(size < 0 for size in shape):
27+
raise ValueError('all elements of broadcast shape must be non-'
28+
'negative')
29+
needs_writeable = not readonly and array.flags.writeable
30+
extras = ['reduce_ok'] if needs_writeable else []
31+
op_flag = 'readwrite' if needs_writeable else 'readonly'
32+
broadcast = np.nditer(
33+
(array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
34+
op_flags=[op_flag], itershape=shape, order='C').itviews[0]
35+
result = _maybe_view_as_subclass(array, broadcast)
36+
if needs_writeable and not result.flags.writeable:
37+
result.flags.writeable = True
38+
return result
39+
40+
41+
# Copy-pasted from numpy.lib.stride_tricks 1.11.2.
42+
def broadcast_to(array, shape, subok=False):
43+
"""Broadcast an array to a new shape.
44+
45+
Parameters
46+
----------
47+
array : array_like
48+
The array to broadcast.
49+
shape : tuple
50+
The shape of the desired array.
51+
subok : bool, optional
52+
If True, then sub-classes will be passed-through, otherwise
53+
the returned array will be forced to be a base-class array (default).
54+
55+
Returns
56+
-------
57+
broadcast : array
58+
A readonly view on the original array with the given shape. It is
59+
typically not contiguous. Furthermore, more than one element of a
60+
broadcasted array may refer to a single memory location.
61+
62+
Raises
63+
------
64+
ValueError
65+
If the array is not compatible with the new shape according to NumPy's
66+
broadcasting rules.
67+
68+
Notes
69+
-----
70+
.. versionadded:: 1.10.0
71+
72+
Examples
73+
--------
74+
>>> x = np.array([1, 2, 3])
75+
>>> np.broadcast_to(x, (3, 3))
76+
array([[1, 2, 3],
77+
[1, 2, 3],
78+
[1, 2, 3]])
79+
"""
80+
return _broadcast_to(array, shape, subok=subok, readonly=True)

lib/matplotlib/afm.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -496,10 +496,7 @@ def get_kern_dist_from_name(self, name1, name2):
496496
Return the kerning pair distance (possibly 0) for chars
497497
*name1* and *name2*
498498
"""
499-
try:
500-
return self._kern[(name1, name2)]
501-
except:
502-
return 0
499+
return self._kern.get((name1, name2), 0)
503500

504501
def get_fontname(self):
505502
"Return the font name, e.g., 'Times-Roman'"

lib/matplotlib/artist.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1435,8 +1435,7 @@ def matchfunc(x):
14351435
elif six.callable(match):
14361436
matchfunc = func
14371437
else:
1438-
raise ValueError('match must be None, an '
1439-
'matplotlib.artist.Artist '
1438+
raise ValueError('match must be None, a matplotlib.artist.Artist '
14401439
'subclass, or a callable')
14411440

14421441
artists = []

lib/matplotlib/backends/backend_gtk.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -561,7 +561,7 @@ def __init__(self, canvas, num):
561561

562562
self.window = gtk.Window()
563563
self.set_window_title("Figure %d" % num)
564-
if (window_icon):
564+
if window_icon:
565565
try:
566566
self.window.set_icon_from_file(window_icon)
567567
except:
@@ -790,13 +790,13 @@ def configure_subplots(self, button):
790790
toolfig.subplots_adjust(top=0.9)
791791
tool = SubplotTool(self.canvas.figure, toolfig)
792792

793-
w = int (toolfig.bbox.width)
794-
h = int (toolfig.bbox.height)
795-
793+
w = int(toolfig.bbox.width)
794+
h = int(toolfig.bbox.height)
796795

797796
window = gtk.Window()
798-
if (window_icon):
799-
try: window.set_icon_from_file(window_icon)
797+
if window_icon:
798+
try:
799+
window.set_icon_from_file(window_icon)
800800
except:
801801
# we presumably already logged a message on the
802802
# failure of the main plot, don't keep reporting
@@ -1056,7 +1056,6 @@ def on_dialog_lineprops_cancelbutton_clicked(self, button):
10561056
# Unfortunately, the SVG renderer (rsvg) leaks memory under earlier
10571057
# versions of pygtk, so we have to use a PNG file instead.
10581058
try:
1059-
10601059
if gtk.pygtk_version < (2, 8, 0) or sys.platform == 'win32':
10611060
icon_filename = 'matplotlib.png'
10621061
else:

lib/matplotlib/backends/backend_gtk3.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -631,9 +631,8 @@ def configure_subplots(self, button):
631631
toolfig.subplots_adjust(top=0.9)
632632
tool = SubplotTool(self.canvas.figure, toolfig)
633633

634-
w = int (toolfig.bbox.width)
635-
h = int (toolfig.bbox.height)
636-
634+
w = int(toolfig.bbox.width)
635+
h = int(toolfig.bbox.height)
637636

638637
window = Gtk.Window()
639638
try:

lib/matplotlib/colors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ def makeMappingArray(N, data, gamma=1.0):
358358

359359
try:
360360
adata = np.array(data)
361-
except:
361+
except Exception:
362362
raise TypeError("data must be convertable to an array")
363363
shape = adata.shape
364364
if len(shape) != 2 or shape[1] != 3:

lib/matplotlib/contour.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1179,8 +1179,8 @@ def _contour_level_args(self, z, args):
11791179
lev = np.asarray(level_arg).astype(np.float64)
11801180
except:
11811181
raise TypeError(
1182-
"Last %s arg must give levels; see help(%s)" %
1183-
(fn, fn))
1182+
"Last {0} arg must give levels; see help({0})"
1183+
.format(fn))
11841184
self.levels = lev
11851185
if self.filled and len(self.levels) < 2:
11861186
raise ValueError("Filled contours require at least 2 levels.")

lib/matplotlib/font_manager.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -566,17 +566,16 @@ def createFontList(fontfiles, fontext='ttf'):
566566
if fontext == 'afm':
567567
try:
568568
fh = open(fpath, 'rb')
569-
except:
569+
except EnvironmentError:
570570
verbose.report("Could not open font file %s" % fpath)
571571
continue
572572
try:
573-
try:
574-
font = afm.AFM(fh)
575-
finally:
576-
fh.close()
573+
font = afm.AFM(fh)
577574
except RuntimeError:
578575
verbose.report("Could not parse font file %s" % fpath)
579576
continue
577+
finally:
578+
fh.close()
580579
try:
581580
prop = afmFontProperty(fpath, font)
582581
except KeyError:

lib/matplotlib/image.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1025,7 +1025,7 @@ def get_cursor_data(self, event):
10251025
i = np.searchsorted(self._Ay, y) - 1
10261026
try:
10271027
return self._A[i, j]
1028-
except:
1028+
except IndexError:
10291029
return None
10301030

10311031

lib/matplotlib/mlab.py

+8-16
Original file line numberDiff line numberDiff line change
@@ -2778,11 +2778,7 @@ def process_skiprows(reader):
27782778

27792779
def ismissing(name, val):
27802780
"Should the value val in column name be masked?"
2781-
2782-
if val == missing or val == missingd.get(name) or val == '':
2783-
return True
2784-
else:
2785-
return False
2781+
return val == missing or val == missingd.get(name) or val == ''
27862782

27872783
def with_default_value(func, default):
27882784
def newfunc(name, val):
@@ -2825,18 +2821,14 @@ def mydate(x):
28252821

28262822
def get_func(name, item, func):
28272823
# promote functions in this order
2828-
funcmap = {mybool: myint, myint: myfloat, myfloat: mydate,
2829-
mydate: mydateparser, mydateparser: mystr}
2830-
try:
2831-
func(name, item)
2832-
except:
2833-
if func == mystr:
2834-
raise ValueError('Could not find a working conversion '
2835-
'function')
2836-
else:
2837-
return get_func(name, item, funcmap[func]) # recurse
2838-
else:
2824+
funcs = [mybool, myint, myfloat, mydate, mydateparser, mystr]
2825+
for func in funcs[funcs.index(func):]:
2826+
try:
2827+
func(name, item)
2828+
except Exception:
2829+
continue
28392830
return func
2831+
raise ValueError('Could not find a working conversion function')
28402832

28412833
# map column names that clash with builtins -- TODO - extend this list
28422834
itemd = {

lib/matplotlib/rcsetup.py

+16-20
Original file line numberDiff line numberDiff line change
@@ -240,11 +240,11 @@ def validate_fonttype(s):
240240
try:
241241
fonttype = validate_int(s)
242242
except ValueError:
243-
if s.lower() in six.iterkeys(fonttypes):
243+
try:
244244
return fonttypes[s.lower()]
245-
raise ValueError(
246-
'Supported Postscript/PDF font types are %s' %
247-
list(six.iterkeys(fonttypes)))
245+
except KeyError:
246+
raise ValueError(
247+
'Supported Postscript/PDF font types are %s' % list(fonttypes))
248248
else:
249249
if fonttype not in six.itervalues(fonttypes):
250250
raise ValueError(
@@ -253,9 +253,8 @@ def validate_fonttype(s):
253253
return fonttype
254254

255255

256-
_validate_standard_backends = ValidateInStrings('backend',
257-
all_backends,
258-
ignorecase=True)
256+
_validate_standard_backends = ValidateInStrings(
257+
'backend', all_backends, ignorecase=True)
259258

260259

261260
def validate_backend(s):
@@ -288,13 +287,11 @@ def validate_maskedarray(v):
288287
' please delete it from your matplotlibrc file')
289288

290289

290+
_seq_err_msg = ('You must supply exactly {n} values, you provided {num} '
291+
'values: {s}')
291292

292-
_seq_err_msg = ('You must supply exactly {n:d} values, you provided '
293-
'{num:d} values: {s}')
294-
295-
_str_err_msg = ('You must supply exactly {n:d} comma-separated values, '
296-
'you provided '
297-
'{num:d} comma-separated values: {s}')
293+
_str_err_msg = ('You must supply exactly {n} comma-separated values, you '
294+
'provided {num} comma-separated values: {s}')
298295

299296

300297
class validate_nseq_float(object):
@@ -466,20 +463,19 @@ def validate_font_properties(s):
466463
['silent', 'helpful', 'debug', 'debug-annoying'])
467464

468465
def validate_whiskers(s):
469-
if s=='range':
466+
if s == 'range':
470467
return 'range'
471468
else:
472469
try:
473470
v = validate_nseq_float(2)(s)
474471
return v
475-
except:
472+
except (TypeError, ValueError):
476473
try:
477474
v = float(s)
478475
return v
479-
except:
480-
err_str = ("Not a valid whisker value ['range',"
481-
"float, (float, float)]")
482-
raise ValueError(err_str)
476+
except ValueError:
477+
raise ValueError("Not a valid whisker value ['range', float, "
478+
"(float, float)]")
483479

484480

485481
def deprecate_savefig_extension(value):
@@ -653,7 +649,7 @@ def __init__(self, vmin, vmax, closedmin=True, closedmax=True):
653649
def __call__(self, s):
654650
try:
655651
s = float(s)
656-
except:
652+
except ValueError:
657653
raise RuntimeError('Value must be a float; found "%s"' % s)
658654

659655
if self.cmin and s < self.vmin:

lib/matplotlib/testing/__init__.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,7 @@ def assert_produces_warning(expected_warning=Warning, filter_level="always",
111111
if not _is_list_like(clear):
112112
clear = [clear]
113113
for m in clear:
114-
try:
115-
m.__warningregistry__.clear()
116-
except:
117-
pass
114+
getattr(m, "__warningregistry__", {}).clear()
118115

119116
saw_warning = False
120117
warnings.simplefilter(filter_level)

0 commit comments

Comments
 (0)