8
8
# Arnaud Joly
9
9
# Denis Engemann
10
10
# Giorgio Patrini
11
+ # Thierry Guillemot
11
12
# License: BSD 3 clause
12
13
import os
13
14
import inspect
@@ -93,8 +94,7 @@ def assert_not_in(x, container):
93
94
# for Python 2
94
95
def assert_raises_regex (expected_exception , expected_regexp ,
95
96
callable_obj = None , * args , ** kwargs ):
96
- """Helper function to check for message patterns in exceptions"""
97
-
97
+ """Helper function to check for message patterns in exceptions."""
98
98
not_raised = False
99
99
try :
100
100
callable_obj (* args , ** kwargs )
@@ -165,7 +165,6 @@ def assert_warns(warning_class, func, *args, **kw):
165
165
result : the return value of `func`
166
166
167
167
"""
168
-
169
168
# very important to avoid uncontrolled state propagation
170
169
clean_warning_registry ()
171
170
with warnings .catch_warnings (record = True ) as w :
@@ -282,17 +281,17 @@ def assert_no_warnings(func, *args, **kw):
282
281
return result
283
282
284
283
285
- def ignore_warnings (obj = None , category = None ):
286
- """ Context manager and decorator to ignore warnings
284
+ def ignore_warnings (obj = None , category = Warning ):
285
+ """Context manager and decorator to ignore warnings.
287
286
288
287
Note. Using this (in both variants) will clear all warnings
289
288
from all python modules loaded. In case you need to test
290
289
cross-module-warning-logging this is not your tool of choice.
291
290
292
291
Parameters
293
292
----------
294
- category : warning class, defaults to None .
295
- The category to filter. If None , all categories will be muted.
293
+ category : warning class, defaults to Warning .
294
+ The category to filter. If Warning , all categories will be muted.
296
295
297
296
Examples
298
297
--------
@@ -305,47 +304,44 @@ def ignore_warnings(obj=None, category=None):
305
304
306
305
>>> ignore_warnings(nasty_warn)()
307
306
42
308
-
309
307
"""
310
-
311
- def _ignore_warnings (fn ):
312
- """Decorator to catch and hide warnings without visual nesting"""
313
- @wraps (fn )
314
- def wrapper (* args , ** kwargs ):
315
- # very important to avoid uncontrolled state propagation
316
- clean_warning_registry ()
317
- with warnings .catch_warnings ():
318
- if category is None :
319
- warnings .simplefilter ("ignore" )
320
- else :
321
- warnings .simplefilter ("ignore" , category )
322
- return fn (* args , ** kwargs )
323
-
324
- return wrapper
325
-
326
308
if callable (obj ):
327
- return _ignore_warnings (obj )
328
- elif category is None :
329
- return _IgnoreWarnings ()
309
+ return _IgnoreWarnings (category = category )(obj )
330
310
else :
331
- return _ignore_warnings
311
+ return _IgnoreWarnings ( category = category )
332
312
333
313
334
314
class _IgnoreWarnings (object ):
315
+ """Improved and simplified Python warnings context manager and decorator.
335
316
336
- """Improved and simplified Python warnings context manager
337
-
317
+ This class allows to ignore the warnings raise by a function.
338
318
Copied from Python 2.7.5 and modified as required.
339
- """
340
319
341
- def __init__ (self ):
342
- """
320
+ Parameters
321
+ ----------
322
+ category : tuple of warning class, defaut to Warning
323
+ The category to filter. By default, all the categories will be muted.
343
324
344
- """
325
+ """
326
+
327
+ def __init__ (self , category ):
345
328
self ._record = True
346
329
self ._module = sys .modules ['warnings' ]
347
330
self ._entered = False
348
331
self .log = []
332
+ self .category = category
333
+
334
+ def __call__ (self , fn ):
335
+ """Decorator to catch and hide warnings without visual nesting."""
336
+ @wraps (fn )
337
+ def wrapper (* args , ** kwargs ):
338
+ # very important to avoid uncontrolled state propagation
339
+ clean_warning_registry ()
340
+ with warnings .catch_warnings ():
341
+ warnings .simplefilter ("ignore" , self .category )
342
+ return fn (* args , ** kwargs )
343
+
344
+ return wrapper
349
345
350
346
def __repr__ (self ):
351
347
args = []
@@ -358,22 +354,13 @@ def __repr__(self):
358
354
359
355
def __enter__ (self ):
360
356
clean_warning_registry () # be safe and not propagate state + chaos
361
- warnings .simplefilter ('always' )
357
+ warnings .simplefilter ("ignore" , self . category )
362
358
if self ._entered :
363
359
raise RuntimeError ("Cannot enter %r twice" % self )
364
360
self ._entered = True
365
361
self ._filters = self ._module .filters
366
362
self ._module .filters = self ._filters [:]
367
363
self ._showwarning = self ._module .showwarning
368
- if self ._record :
369
- self .log = []
370
-
371
- def showwarning (* args , ** kwargs ):
372
- self .log .append (warnings .WarningMessage (* args , ** kwargs ))
373
- self ._module .showwarning = showwarning
374
- return self .log
375
- else :
376
- return None
377
364
378
365
def __exit__ (self , * exc_info ):
379
366
if not self ._entered :
@@ -412,7 +399,7 @@ def _assert_allclose(actual, desired, rtol=1e-7, atol=0,
412
399
413
400
414
401
def assert_raise_message (exceptions , message , function , * args , ** kwargs ):
415
- """Helper function to test error messages in exceptions
402
+ """Helper function to test error messages in exceptions.
416
403
417
404
Parameters
418
405
----------
@@ -621,8 +608,8 @@ def is_abstract(c):
621
608
all_classes = set (all_classes )
622
609
623
610
estimators = [c for c in all_classes
624
- if (issubclass (c [1 ], BaseEstimator )
625
- and c [0 ] != 'BaseEstimator' )]
611
+ if (issubclass (c [1 ], BaseEstimator ) and
612
+ c [0 ] != 'BaseEstimator' )]
626
613
# get rid of abstract base classes
627
614
estimators = [c for c in estimators if not is_abstract (c [1 ])]
628
615
@@ -652,7 +639,8 @@ def is_abstract(c):
652
639
estimators = filtered_estimators
653
640
if type_filter :
654
641
raise ValueError ("Parameter type_filter must be 'classifier', "
655
- "'regressor', 'transformer', 'cluster' or None, got"
642
+ "'regressor', 'transformer', 'cluster' or "
643
+ "None, got"
656
644
" %s." % repr (type_filter ))
657
645
658
646
# drop duplicates, sort for reproducibility
@@ -667,7 +655,6 @@ def set_random_state(estimator, random_state=0):
667
655
Classes for whom random_state is deprecated are ignored. Currently DBSCAN
668
656
is one such class.
669
657
"""
670
-
671
658
if isinstance (estimator , DBSCAN ):
672
659
return
673
660
@@ -676,8 +663,7 @@ def set_random_state(estimator, random_state=0):
676
663
677
664
678
665
def if_matplotlib (func ):
679
- """Test decorator that skips test if matplotlib not installed. """
680
-
666
+ """Test decorator that skips test if matplotlib not installed."""
681
667
@wraps (func )
682
668
def run_test (* args , ** kwargs ):
683
669
try :
@@ -728,7 +714,7 @@ def func(*args, **kwargs):
728
714
729
715
730
716
def if_safe_multiprocessing_with_blas (func ):
731
- """Decorator for tests involving both BLAS calls and multiprocessing
717
+ """Decorator for tests involving both BLAS calls and multiprocessing.
732
718
733
719
Under POSIX (e.g. Linux or OSX), using multiprocessing in conjunction with
734
720
some implementation of BLAS (or other libraries that manage an internal
@@ -745,7 +731,6 @@ def if_safe_multiprocessing_with_blas(func):
745
731
for multiprocessing to avoid this issue. However it can cause pickling
746
732
errors on interactively defined functions. It therefore not enabled by
747
733
default.
748
-
749
734
"""
750
735
@wraps (func )
751
736
def run_test (* args , ** kwargs ):
@@ -757,7 +742,7 @@ def run_test(*args, **kwargs):
757
742
758
743
759
744
def clean_warning_registry ():
760
- """Safe way to reset warnings """
745
+ """Safe way to reset warnings. """
761
746
warnings .resetwarnings ()
762
747
reg = "__warningregistry__"
763
748
for mod_name , mod in list (sys .modules .items ()):
@@ -780,7 +765,9 @@ def check_skip_travis():
780
765
781
766
def _delete_folder (folder_path , warn = False ):
782
767
"""Utility function to cleanup a temporary folder if still existing.
783
- Copy from joblib.pool (for independence)"""
768
+
769
+ Copy from joblib.pool (for independence).
770
+ """
784
771
try :
785
772
if os .path .exists (folder_path ):
786
773
# This can fail under windows,
0 commit comments