8000 MNT Use raise from in 19 modules · scikit-learn/scikit-learn@ca06555 · GitHub
[go: up one dir, main page]

Skip to content

Commit ca06555

Browse files
committed
MNT Use raise from in 19 modules
1 parent ae7667c commit ca06555

File tree

17 files changed

+95
-89
lines changed

17 files changed

+95
-89
lines changed

benchmarks/bench_tsne_mnist.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def sanitize(filename):
106106
if args.bhtsne:
107107
try:
108108
from bhtsne.bhtsne import run_bh_tsne
109-
except ImportError:
109+
except ImportError as e:
110110
raise ImportError("""\
111111
If you want comparison with the reference implementation, build the
112112
binary from source (https://github.com/lvdmaaten/bhtsne) in the folder
@@ -117,7 +117,7 @@ def sanitize(filename):
117117
$ g++ sptree.cpp tsne.cpp tsne_main.cpp -o bh_tsne -O2
118118
$ touch __init__.py
119119
$ cd ..
120-
""")
120+
""") from e
121121

122122
def bhtsne(X):
123123
"""Wrapper for the reference lvdmaaten/bhtsne implementation."""
@@ -131,10 +131,10 @@ def bhtsne(X):
131131

132132
try:
133133
from memory_profiler import profile
134-
except ImportError:
134+
except ImportError as e:
135135
raise ImportError("To run the benchmark with `--profile`, you "
136136
"need to install `memory_profiler`. Please "
137-
"run `pip install memory_profiler`.")
137+
"run `pip install memory_profiler`.") from e
138138
methods = [(n, profile(m)) for n, m in methods]
139139

140140
data_size = [100, 500, 1000, 5000, 10000]

doc/tutorial/machine_learning_map/parse_path.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ def Sequence(token):
5454
def convertToFloat(s, loc, toks):
5555
try:
5656
return float(toks[0])
57-
except:
58-
raise ParseException(loc, "invalid float format %s"%toks[0])
57+
except BaseException as e:
58+
raise ParseException(loc, "invalid float format %s" % toks[0]) from e
5959

6060
exponent = CaselessLiteral("e")+Optional(sign)+Word(nums)
6161

doc/tutorial/machine_learning_map/pyparsing.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1354,8 +1354,8 @@ def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
13541354
try:
13551355
try:
13561356
loc,tokens = self.parseImpl( instring, preloc, doActions )
1357-
except IndexError:
1358-
raise ParseException( instring, len(instring), self.errmsg, self )
1357+
except IndexError as e:
1358+
raise ParseException( instring, len(instring), self.errmsg, self ) from e
13591359
except ParseBaseException as err:
13601360
#~ print ("Exception raised:", err)
13611361
if self.debugActions[2]:
@@ -1372,8 +1372,8 @@ def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
13721372
if self.mayIndexError or loc >= len(instring):
13731373
try:
13741374
loc,tokens = self.parseImpl( instring, preloc, doActions )
1375-
except IndexError:
1376-
raise ParseException( instring, len(instring), self.errmsg, self )
1375+
except IndexError as e:
1376+
raise ParseException( instring, len(instring), self.errmsg, self ) from e
13771377
else:
13781378
loc,tokens = self.parseImpl( instring, preloc, doActions )
13791379

@@ -1414,9 +1414,9 @@ def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
14141414
def tryParse( self, instring, loc ):
14151415
try:
14161416
return self._parse( instring, loc, doActions=False )[0]
1417-
except ParseFatalException:
1418-
raise ParseException( instring, loc, self.errmsg, self)
1419-
1417+
except ParseFatalException as e:
1418+
raise ParseException( instring, loc, self.errmsg, self) from e
1419+
14201420
def canParseNext(self, instring, loc):
14211421
try:
14221422
self.tryParse(instring, loc)
@@ -3383,9 +3383,9 @@ def parseImpl( self, instring, loc, doActions=True ):
33833383
raise
33843384
except ParseBaseException as pe:
33853385
pe.__traceback__ = None
3386-
raise ParseSyntaxException._from_exception(pe)
3387-
except IndexError:
3388-
raise ParseSyntaxException(instring, len(instring), self.errmsg, self)
3386+
raise ParseSyntaxException._from_exception(pe) from pe
3387+
except IndexError as e:
3388+
raise ParseSyntaxException(instring, len(instring), self.errmsg, self) from e
33893389
else:
33903390
loc, exprtokens = e._parse( instring, loc, doActions )
33913391
if exprtokens or exprtokens.haskeys():
@@ -5581,7 +5581,7 @@ def cvt_fn(s,l,t):
55815581
try:
55825582
return datetime.strptime(t[0], fmt).date()
55835583
except ValueError as ve:
5584-
raise ParseException(s, l, str(ve))
5584+
raise ParseException(s, l, str(ve)) from ve
55855585
return cvt_fn
55865586

55875587
@staticmethod
@@ -5603,7 +5603,7 @@ def cvt_fn(s,l,t):
56035603
try:
56045604
return datetime.strptime(t[0], fmt)
56055605
except ValueError as ve:
5606-
raise ParseException(s, l, str(ve))
5606+
raise ParseException(s, l, str(ve)) from ve
56075607
return cvt_fn
56085608

56095609
iso8601_date = Regex(r'(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?').setName("ISO8601 date")

sklearn/_build_utils/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ def _check_cython_version():
2525
CYTHON_MIN_VERSION)
2626
try:
2727
import Cython
28-
except ModuleNotFoundError:
28+
except ModuleNotFoundError as e:
2929
# Re-raise with more informative error message instead:
30-
raise ModuleNotFoundError(message)
30+
raise ModuleNotFoundError(message) from e
3131

3232
if LooseVersion(Cython.__version__) < CYTHON_MIN_VERSION:
3333
message += (' The current version of Cython is {} installed in {}.'

sklearn/cluster/_agglomerative.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,10 +430,11 @@ def linkage_tree(X, connectivity=None, n_clusters=None, linkage='complete',
430430
'single': None} # Single linkage is handled differently
431431
try:
432432
join_func = linkage_choices[linkage]
433-
except KeyError:
433+
except KeyError as e:
434434
raise ValueError(
435435
'Unknown linkage option, linkage should be one '
436-
'of %s, but %s was given' % (linkage_choices.keys(), linkage))
436+
'of %s, but %s was given' % (linkage_choices.keys(), linkage)
437+
) from e
437438

438439
if affinity == 'cosine' and np.any(~np.any(X, axis=1)):
439440
raise ValueError(

sklearn/cluster/_bicluster.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -466,11 +466,11 @@ def _check_parameters(self):
466466
r, c = self.n_clusters
467467
int(r)
468468
int(c)
469-
except (ValueError, TypeError):
469+
except (ValueError, TypeError) as e:
470470
raise ValueError("Incorrect parameter n_clusters has value:"
471471
" {}. It should either be a single integer"
472472
" or an iterable with two integers:"
473-
" (n_row_clusters, n_column_clusters)")
473+
" (n_row_clusters, n_column_clusters)") from e
474474
if self.n_components < 1:
475475
raise ValueError("Parameter n_components must be greater than 0,"
476476
" but its value is {}".format(self.n_components))

sklearn/compose/_column_transformer.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ def _fit_transform(self, X, y, func, fitted=False):
467467
self._iter(fitted=fitted, replace_strings=True), 1))
468468
except ValueError as e:
469469
if "Expected 2D array, got 1D array instead" in str(e):
470-
raise ValueError(_ERR_MSG_1DCOLUMN)
470+
raise ValueError(_ERR_MSG_1DCOLUMN) from e
471471
else:
472472
raise
473473

@@ -629,9 +629,11 @@ def _hstack(self, Xs):
629629
accept_sparse=True,
630630
force_all_finite=False)
631631
for X in Xs]
632-
except ValueError:
633-
raise ValueError("For a sparse output, all columns should"
634-
" be a numeric or convertible to a numeric.")
632+
except ValueError as e:
633+
raise ValueError(
634+
"For a sparse output, all columns should "
635+
"be a numeric or convertible to a numeric."
636+
) from e
635637

636638
return sparse.hstack(converted_Xs).tocsr()
637639
else:

sklearn/datasets/_samples_generator.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -650,9 +650,9 @@ def make_circles(n_samples=100, *, shuffle=True, noise=None, random_state=None,
650650
else:
651651
try:
652652
n_samples_out, n_samples_in = n_samples
653-
except ValueError:
653+
except ValueError as e:
654654
raise ValueError('`n_samples` can be either an int or '
655-
'a two-element tuple.')
655+
'a two-element tuple.') from e
656656

657657
generator = check_random_state(random_state)
658658
# so as not to have the first point = last point, we set endpoint=False
@@ -715,9 +715,9 @@ def make_moons(n_samples=100, *, shuffle=True, noise=None, random_state=None):
715715
else:
716716
try:
717717
n_samples_out, n_samples_in = n_samples
718-
except ValueError:
718+
except ValueError as e:
719719
raise ValueError('`n_samples` can be either an int or '
720-
'a two-element tuple.')
720+
'a two-element tuple.') from e
721721

722722
generator = check_random_state(random_state)
723723

@@ -845,13 +845,14 @@ def make_blobs(n_samples=100, n_features=2, *, centers=None, cluster_std=1.0,
845845
size=(n_centers, n_features))
846846
try:
847847
assert len(centers) == n_centers
848-
except TypeError:
848+
except TypeError as e:
849849
raise ValueError("Parameter `centers` must be array-like. "
850-
"Got {!r} instead".format(centers))
851-
except AssertionError:
852-
raise ValueError("Length of `n_samples` not consistent"
853-
" with number of centers. Got n_samples = {} "
854-
"and centers = {}".format(n_samples, centers))
850+
"Got {!r} instead".format(centers)) from e
851+
except AssertionError as e:
852+
raise ValueError(
853+
f"Length of `n_samples` not consistent with number of "
854+
f"centers. Got n_samples = {n_samples} and centers = {centers}"
855+
) from e
855856
else:
856857
centers = check_array(centers)
857858
n_features = centers.shape[1]

sklearn/ensemble/_gb.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -456,8 +456,9 @@ def fit(self, X, y, sample_weight=None, monitor=None):
456456
"weights.".format(self.init_.__class__.__name__))
457457
try:
458458
self.init_.fit(X, y, sample_weight=sample_weight)
459-
except TypeError: # regular estimator without SW support
460-
raise ValueError(msg)
459+
except TypeError as e:
460+
# regular estimator without SW support
461+
raise ValueError(msg) from e
461462
except ValueError as e:
462463
if "pass parameters to specific steps of "\
463464
"your pipeline using the "\
@@ -1219,9 +1220,9 @@ def predict_proba(self, X):
12191220
return self.loss_._raw_prediction_to_proba(raw_predictions)
12201221
except NotFittedError:
12211222
raise
1222-
except AttributeError:
1223+
except AttributeError as e:
12231224
raise AttributeError('loss=%r does not support predict_proba' %
1224-
self.loss)
1225+
self.loss) from e
12251226

12261227
def predict_log_proba(self, X):
12271228
"""Predict class log-probabilities for X.
@@ -1270,9 +1271,9 @@ def staged_predict_proba(self, X):
12701271
yield self.loss_._raw_prediction_to_proba(raw_predictions)
12711272
except NotFittedError:
12721273
raise
1273-
except AttributeError:
1274+
except AttributeError as e:
12741275
raise AttributeError('loss=%r does not support predict_proba' %
1275-
self.loss)
1276+
self.loss) from e
12761277

12771278

12781279
class GradientBoostingRegressor(RegressorMixin, BaseGradientBoosting):

sklearn/ensemble/_weight_boosting.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -255,11 +255,11 @@ def feature_importances_(self):
255255
in zip(self.estimator_weights_, self.estimators_))
256256
/ norm)
257257

258-
except AttributeError:
258+
except AttributeError as e:
259259
raise AttributeError(
260260
"Unable to compute feature importances "
261261
"since base_estimator does not have a "
262-
"feature_importances_ attribute")
262+
"feature_importances_ attribute") from e
263263

264264

265265
def _samme_proba(estimator, n_classes, X):

sklearn/externals/_arff.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,8 @@ def _escape_sub_callback(match):
265265
if len(s) == 2:
266266
try:
267267
return _ESCAPE_SUB_MAP[s]
268-
except KeyError:
269-
raise ValueError('Unsupported escape sequence: %s' % s)
268+
except KeyError as e:
269+
raise ValueError('Unsupported escape sequence: %s' % s) from e
270270
if s[1] == 'u':
271271
return unichr(int(s[2:], 16))
272272
else:
@@ -303,8 +303,8 @@ def _parse_values(s):
303303
# an ARFF syntax error in sparse data
304304
for match in _RE_SPARSE_KEY_VALUES.finditer(s):
305305
if not match.group(1):
306-
raise BadLayout('Error parsing %r' % match.group())
307-
raise BadLayout('Unknown parsing error')
306+
raise BadLayout('Error parsing %r' % match.group()) from exc
307+
raise BadLayout('Unknown parsing error') from exc
308308
else:
309309
# an ARFF syntax error
310310
for match in _RE_DENSE_VALUES.finditer(s):
@@ -449,8 +449,8 @@ def __init__(self, values):
449449
def __call__(self, value):
450450
try:
451451
return self.values[value]
452-
except KeyError:
453-
raise BadNominalValue(value)
452+
except KeyError as e:
453+
raise BadNominalValue(value) from e
454454

455455

456456
class NominalConversor(object):
@@ -498,7 +498,7 @@ def _decode_values(values, conversors):
498498
in zip(conversors, values)]
499499
except ValueError as exc:
500500
if 'float: ' in str(exc):
501-
raise BadNumericalValue()
501+
raise BadNumericalValue from exc
502502
return values
503503

504504
def encode_data(self, data, attributes):
@@ -557,11 +557,11 @@ def decode_rows(self, stream, conversors):
557557
for key, value in zip(row_cols, values)]
558558
except ValueError as exc:
559559
if 'float: ' in str(exc):
560-
raise BadNumericalValue()
560+
raise BadNumericalValue from exc
561561
raise
562-
except IndexError:
562+
except IndexError as e:
563563
# conversor out of range
564-
raise BadDataFormat(row)
564+
raise BadDataFormat(row) from e
565565

566566
data.extend(values)
567567
rows.extend([i] * len(values))
@@ -617,11 +617,11 @@ def decode_rows(self, stream, conversors):
617617
for key, value in values.items()}
618618
except ValueError as exc:
619619
if 'float: ' in str(exc):
620-
raise BadNumericalValue()
620+
raise BadNumericalValue from exc
621621
raise
622-
except IndexError:
622+
except IndexError as e:
623623
# conversor out of range
624-
raise BadDataFormat(row)
624+
raise BadDataFormat(row) from e
625625

626626
def encode_data(self, data, attributes):
627627
current_row = 0
@@ -772,8 +772,8 @@ def _decode_attribute(self, s):
772772
if _RE_TYPE_NOMINAL.match(type_):
773773
try:
774774
type_ = _parse_values(type_.strip('{} '))
775-
except Exception:
776-
raise BadAttributeType()
775+
except Exception as e:
776+
raise BadAttributeType from e
777777
if isinstance(type_, dict):
778778
raise BadAttributeType()
779779

sklearn/externals/_lobpcg.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -384,8 +384,8 @@ def lobpcg(A, X,
384384
try:
385385
# gramYBY is a Cholesky factor from now on...
386386
gramYBY = cho_factor(gramYBY)
387-
except LinAlgError:
388-
raise ValueError('cannot handle linearly dependent constraints')
387+
except LinAlgError as e:
388+
raise ValueError('cannot handle linearly dependent constraints') from e
389389

390390
_applyConstraints(blockVectorX, gramYBY, blockVectorBY, blockVectorY)
391391

@@ -610,8 +610,8 @@ def _handle_gramA_gramB_verbosity(gramA, gramB):
610610
try:
611611
_lambda, eigBlockVector = eigh(gramA, gramB,
612612
check_finite=False)
613-
except LinAlgError:
614-
raise ValueError('eigh has failed in lobpcg iterations')
613+
except LinAlgError as e:
614+
raise ValueError('eigh has failed in lobpcg iterations') from e
615615

616616
ii = _get_indx(_lambda, sizeX, largest)
617617
if verbosityLevel > 10:

sklearn/inspection/_partial_dependence.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,9 @@ def _partial_dependence_brute(est, grid, features, X, response_method):
164164
predictions.append(pred)
165165
# average over samples
166166
averaged_predictions.append(np.mean(pred, axis=0))
167-
except NotFittedError:
167+
except NotFittedError as e:
168168
raise ValueError(
169-
"'estimator' parameter must be a fitted estimator")
169+
"'estimator' parameter must be a fitted estimator") from e
170170

171171
n_samples = X.shape[0]
172172

0 commit comments

Comments
 (0)
0