Skip to content

Instantly share code, notes, and snippets.

@wolph
Created October 5, 2015 09:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolph/ebebe5d693fe6d0ad1c8 to your computer and use it in GitHub Desktop.
Save wolph/ebebe5d693fe6d0ad1c8 to your computer and use it in GitHub Desktop.
Decorator to ignore a specific number of Python warnings
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