Created
October 5, 2015 09:08
-
-
Save wolph/ebebe5d693fe6d0ad1c8 to your computer and use it in GitHub Desktop.
Decorator to ignore a specific number of Python warnings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import warnings | |
import functools | |
def ignore_warning(warning, count=None): | |
def _ignore_warning(function): | |
@functools.wraps(function) | |
def __ignore_warning(*args, **kwargs): | |
with warnings.catch_warnings(record=True) as ws: | |
# Catch all warnings of this type | |
warnings.simplefilter('always', warning) | |
# Execute the function | |
result = function(*args, **kwargs) | |
# If we are looking for a specific amount of | |
# warnings, re-send all extra warnings | |
if count is not None: | |
for w in ws[count:]: | |
warnings.showwarning( | |
message=w.message, | |
category=w.category, | |
filename=w.filename, | |
lineno=w.lineno, | |
file=w.file, | |
line=w.line, | |
) | |
return result | |
return __ignore_warning | |
return _ignore_warning |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment