Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a53a04c

Browse files
authored
Merge pull request #10336 from anntzer/instancechecks
MNT: Use Integral and Real in typechecks rather than explicit types.
2 parents 51f6ef8 + 8c8427f commit a53a04c

File tree

8 files changed

+48
-55
lines changed

8 files changed

+48
-55
lines changed

lib/matplotlib/axes/_base.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import itertools
33
import logging
44
import math
5+
from numbers import Real
56
from operator import attrgetter
67
import types
78
import warnings
@@ -10,7 +11,7 @@
1011

1112
import matplotlib
1213

13-
from matplotlib import cbook
14+
from matplotlib import cbook, rcParams
1415
from matplotlib.cbook import (_check_1d, _string_to_bool, iterable,
1516
index_of, get_label)
1617
from matplotlib import docstring
@@ -30,13 +31,10 @@
3031
from matplotlib.artist import allow_rasterization
3132
from matplotlib.legend import Legend
3233

33-
from matplotlib.rcsetup import cycler
34-
from matplotlib.rcsetup import validate_axisbelow
34+
from matplotlib.rcsetup import cycler, validate_axisbelow
3535

3636
_log = logging.getLogger(__name__)
3737

38-
rcParams = matplotlib.rcParams
39-
4038

4139
def _process_plot_format(fmt):
4240
"""
@@ -3003,9 +3001,8 @@ def _validate_converted_limits(self, limit, convert):
30033001
"""
30043002
if limit is not None:
30053003
converted_limit = convert(limit)
3006-
if (isinstance(converted_limit, float) and
3007-
(not np.isreal(converted_limit) or
3008-
not np.isfinite(converted_limit))):
3004+
if (isinstance(converted_limit, Real)
3005+
and not np.isfinite(converted_limit)):
30093006
raise ValueError("Axis limits cannot be NaN or Inf")
30103007
return converted_limit
30113008

lib/matplotlib/backends/qt_editor/formlayout.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242

4343
import copy
4444
import datetime
45+
from numbers import Integral, Real
4546
import warnings
4647

4748
from matplotlib import colors as mcolors
@@ -137,7 +138,7 @@ def tuple_to_qfont(tup):
137138
"""
138139
if not (isinstance(tup, tuple) and len(tup) == 4
139140
and font_is_installed(tup[0])
140-
and isinstance(tup[1], int)
141+
and isinstance(tup[1], Integral)
141142
and isinstance(tup[2], bool)
142143
and isinstance(tup[3], bool)):
143144
return None
@@ -256,7 +257,7 @@ def setup(self):
256257
selindex = value.index(selindex)
257258
elif selindex in keys:
258259
selindex = keys.index(selindex)
259-
elif not isinstance(selindex, int):
260+
elif not isinstance(selindex, Integral):
260261
warnings.warn(
261262
"index '%s' is invalid (label: %s, value: %s)" %
262263
(selindex, label, value), stacklevel=2)
@@ -268,18 +269,18 @@ def setup(self):
268269
field.setCheckState(QtCore.Qt.Checked)
269270
else:
270271
field.setCheckState(QtCore.Qt.Unchecked)
271-
elif isinstance(value, float):
272+
elif isinstance(value, Integral):
273+
field = QtWidgets.QSpinBox(self)
274+
field.setRange(-1e9, 1e9)
275+
field.setValue(value)
276+
elif isinstance(value, Real):
272277
field = QtWidgets.QLineEdit(repr(value), self)
273278
field.setCursorPosition(0)
274279
field.setValidator(QtGui.QDoubleValidator(field))
275280
field.validator().setLocale(QtCore.QLocale("C"))
276281
dialog = self.get_dialog()
277282
dialog.register_float_field(field)
278283
field.textChanged.connect(lambda text: dialog.update_buttons())
279-
elif isinstance(value, int):
280-
field = QtWidgets.QSpinBox(self)
281-
field.setRange(-1e9, 1e9)
282-
field.setValue(value)
283284
elif isinstance(value, datetime.datetime):
284285
field = QtWidgets.QDateTimeEdit(self)
285286
field.setDateTime(value)
@@ -310,10 +311,10 @@ def get(self):
310311
value = value[index]
311312
elif isinstance(value, bool):
312313
value = field.checkState() == QtCore.Qt.Checked
313-
elif isinstance(value, float):
314-
value = float(str(field.text()))
315-
elif isinstance(value, int):
314+
elif isinstance(value, Integral):
316315
value = int(field.value())
316+
elif isinstance(value, Real):
317+
value = float(str(field.text()))
317318
elif isinstance(value, datetime.datetime):
318319
value = field.dateTime().toPyDateTime()
319320
elif isinstance(value, datetime.date):

lib/matplotlib/blocking_input.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@
2323
from numbers import Integral
2424

2525
import matplotlib.lines as mlines
26-
import numpy as np
27-
2826

2927
_log = logging.getLogger(__name__)
3028

lib/matplotlib/contour.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
These are classes to support contour plotting and labelling for the Axes class.
33
"""
44

5+
from numbers import Integral
56
import warnings
67

78
import numpy as np
@@ -1205,7 +1206,7 @@ def _contour_level_args(self, z, args):
12051206
else:
12061207
level_arg = args[0]
12071208
try:
1208-
if type(level_arg) == int:
1209+
if isinstance(level_arg, Integral):
12091210
lev = self._autolev(level_arg)
12101211
else:
12111212
lev = np.asarray(level_arg).astype(np.float64)

lib/matplotlib/figure.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"""
1313

1414
import logging
15+
from numbers import Integral
1516
import warnings
1617

1718
import numpy as np
@@ -1292,7 +1293,7 @@ def add_subplot(self, *args, **kwargs):
12921293
if not len(args):
12931294
return
12941295

1295-
if len(args) == 1 and isinstance(args[0], int):
1296+
if len(args) == 1 and isinstance(args[0], Integral):
12961297
if not 100 <= args[0] <= 999:
12971298
raise ValueError("Integer subplot specification must be a "
12981299
"three-digit number, not {}".format(args[0]))
@@ -1456,7 +1457,7 @@ def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False,
14561457
# In most cases, no error will ever occur, but mysterious behavior
14571458
# will result because what was intended to be the subplot index is
14581459
# instead treated as a bool for sharex.
1459-
if isinstance(sharex, int):
1460+
if isinstance(sharex, Integral):
14601461
warnings.warn(
14611462
"sharex argument to subplots() was an integer. "
14621463
"Did you intend to use subplot() (without 's')?")

lib/matplotlib/lines.py

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"""
55

66
# TODO: expose cap and join style attrs
7-
from numbers import Number
7+
from numbers import Integral, Number, Real
88
import warnings
99

1010
import numpy as np
@@ -127,41 +127,37 @@ def _slice_or_none(in_v, slc):
127127
return None
128128
return in_v[slc]
129129

130-
# if just a float, assume starting at 0.0 and make a tuple
131-
if isinstance(markevery, float):
132-
markevery = (0.0, markevery)
133130
# if just an int, assume starting at 0 and make a tuple
134-
elif isinstance(markevery, int):
131+
if isinstance(markevery, Integral):
135132
markevery = (0, markevery)
136-
# if just an numpy int, assume starting at 0 and make a tuple
137-
elif isinstance(markevery, np.integer):
138-
markevery = (0, markevery.item())
133+
# if just a float, assume starting at 0.0 and make a tuple
134+
elif isinstance(markevery, Real):
135+
markevery = (0.0, markevery)
139136

140137
if isinstance(markevery, tuple):
141138
if len(markevery) != 2:
142-
raise ValueError('`markevery` is a tuple but its '
143-
'len is not 2; '
144-
'markevery=%s' % (markevery,))
139+
raise ValueError('`markevery` is a tuple but its len is not 2; '
140+
'markevery={}'.format(markevery))
145141
start, step = markevery
146142
# if step is an int, old behavior
147-
if isinstance(step, int):
148-
#tuple of 2 int is for backwards compatibility,
149-
if not(isinstance(start, int)):
150-
raise ValueError('`markevery` is a tuple with '
151-
'len 2 and second element is an int, but '
152-
'the first element is not an int; '
153-
'markevery=%s' % (markevery,))
143+
if isinstance(step, Integral):
144+
# tuple of 2 int is for backwards compatibility,
145+
if not isinstance(start, Integral):
146+
raise ValueError(
147+
'`markevery` is a tuple with len 2 and second element is '
148+
'an int, but the first element is not an int; markevery={}'
149+
.format(markevery))
154150
# just return, we are done here
155151

156152
return Path(verts[slice(start, None, step)],
157153
_slice_or_none(codes, slice(start, None, step)))
158154

159-
elif isinstance(step, float):
160-
if not isinstance(start, (int, float)):
155+
elif isinstance(step, Real):
156+
if not isinstance(start, Real):
161157
raise ValueError(
162158
'`markevery` is a tuple with len 2 and second element is '
163159
'a float, but the first element is not a float or an int; '
164-
'markevery=%s' % (markevery,))
160+
'markevery={}'.format(markevery))
165161
# calc cumulative distance along path (in display coords):
166162
disp_coords = affine.transform(tpath.vertices)
167163
delta = np.empty((len(disp_coords), 2))
@@ -192,14 +188,12 @@ def _slice_or_none(in_v, slc):
192188

193189
elif isinstance(markevery, slice):
194190
# mazol tov, it's already a slice, just return
195-
return Path(verts[markevery],
196-
_slice_or_none(codes, markevery))
191+
return Path(verts[markevery], _slice_or_none(codes, markevery))
197192

198193
elif iterable(markevery):
199194
#fancy indexing
200195
try:
201-
return Path(verts[markevery],
202-
_slice_or_none(codes, markevery))
196+
return Path(verts[markevery], _slice_or_none(codes, markevery))
203197

204198
except (ValueError, IndexError):
205199
raise ValueError('`markevery` is iterable but '
@@ -822,7 +816,7 @@ def draw(self, renderer):
822816
subsampled = tpath
823817

824818
snap = marker.get_snap_threshold()
825-
if type(snap) == float:
819+
if isinstance(snap, Real):
826820
snap = renderer.points_to_pixels(self._markersize) >= snap
827821
gc.set_snap(snap)
828822
gc.set_joinstyle(marker.get_joinstyle())

lib/matplotlib/widgets.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010
"""
1111

1212
import copy
13+
from numbers import Integral
1314

1415
import numpy as np
15-
from matplotlib import rcParams
1616

17-
from .patches import Circle, Rectangle, Ellipse
17+
from . import rcParams
1818
from .lines import Line2D
19+
from .patches import Circle, Rectangle, Ellipse
1920
from .transforms import blended_transform_factory
2021

2122

@@ -1454,7 +1455,7 @@ def __init__(self, ax, onselect, useblit=False, button=None,
14541455
self.background = None
14551456
self.artists = []
14561457

1457-
if isinstance(button, int):
1458+
if isinstance(button, Integral):
14581459
self.validButtons = [button]
14591460
else:
14601461
self.validButtons = button

lib/mpl_toolkits/axes_grid1/axes_grid.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,9 @@ def __init__(self, fig,
185185
axes_class = self._defaultLocatableAxesClass
186186
axes_class_args = {}
187187
else:
188-
if (type(axes_class)) == type and \
189-
issubclass(axes_class,
190-
self._defaultLocatableAxesClass.Axes):
188+
if (isinstance(axes_class, type)
189+
and issubclass(axes_class,
190+
self._defaultLocatableAxesClass.Axes)):
191191
axes_class_args = {}
192192
else:
193193
axes_class, axes_class_args = axes_class

0 commit comments

Comments
 (0)