In Python 2.6 it is possible to suppress warnings from the warnings module by using
with warnings.catch_warnings():
warnings.simplefilter("ignore")
fxn()
Versions of Python before 2.6 don't support with
however, so I'm wondering if there alternatives to the above that would work with pre-2.6 versions?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With