This is similar:
# Save the existing list of warning filters before we modify it using simplefilter().
# Note: the '[:]' causes a copy of the list to be created. Without it, original_filter
# would alias the one and only 'real' list and then we'd have nothing to restore.
original_filters = warnings.filters[:]
# Ignore warnings.
warnings.simplefilter("ignore")
try:
# Execute the code that presumably causes the warnings.
fxn()
finally:
# Restore the list of warning filters.
warnings.filters = original_filters
Edit: Without the try/finally
, the original warning filters would not be restored if fxn() threw an exception. See PEP 343 for more discussion on how the with
statement serves to replace try/finally
when used like this.