Context manager and decorator to ignore warnings. Note: Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging, this is not your tool of choice. Parameters ---------- obj : callable, defaul
(obj=None, category=Warning)
| 71 | |
| 72 | |
| 73 | def ignore_warnings(obj=None, category=Warning): |
| 74 | """Context manager and decorator to ignore warnings. |
| 75 | |
| 76 | Note: Using this (in both variants) will clear all warnings |
| 77 | from all python modules loaded. In case you need to test |
| 78 | cross-module-warning-logging, this is not your tool of choice. |
| 79 | |
| 80 | Parameters |
| 81 | ---------- |
| 82 | obj : callable, default=None |
| 83 | callable where you want to ignore the warnings. |
| 84 | category : warning class, default=Warning |
| 85 | The category to filter. If Warning, all categories will be muted. |
| 86 | |
| 87 | Examples |
| 88 | -------- |
| 89 | >>> import warnings |
| 90 | >>> from sklearn.utils._testing import ignore_warnings |
| 91 | >>> with ignore_warnings(): |
| 92 | ... warnings.warn('buhuhuhu') |
| 93 | |
| 94 | >>> def nasty_warn(): |
| 95 | ... warnings.warn('buhuhuhu') |
| 96 | ... print(42) |
| 97 | |
| 98 | >>> ignore_warnings(nasty_warn)() |
| 99 | 42 |
| 100 | """ |
| 101 | if isinstance(obj, type) and issubclass(obj, Warning): |
| 102 | # Avoid common pitfall of passing category as the first positional |
| 103 | # argument which result in the test not being run |
| 104 | warning_name = obj.__name__ |
| 105 | raise ValueError( |
| 106 | "'obj' should be a callable where you want to ignore warnings. " |
| 107 | "You passed a warning class instead: 'obj={warning_name}'. " |
| 108 | "If you want to pass a warning class to ignore_warnings, " |
| 109 | "you should use 'category={warning_name}'".format(warning_name=warning_name) |
| 110 | ) |
| 111 | elif callable(obj): |
| 112 | return _IgnoreWarnings(category=category)(obj) |
| 113 | else: |
| 114 | return _IgnoreWarnings(category=category) |
| 115 | |
| 116 | |
| 117 | class _IgnoreWarnings: |
no test coverage detected
searching dependent graphs…