views:

157

answers:

2

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?

+1  A: 

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.

Jon-Eric
Thanks! Could you explain how and why this works?
astrofrog
Morgoth: It makes a copy of the filters, modifies them, calls fxn, and finally resets the filters to the original value. Pretty much the exact same thing the 2.6 context manager does.
Roger Pate
Thanks for the explanation - why is the try ... finally needed?
astrofrog
I've added comments to explain the code and a note about why the try ... finally is better.
Jon-Eric
+1  A: 

Depending on what the minimum version you need to support using Python 2.5's

from __future__ import with_statement

might be an option, else you'll probably need to fallback to what Jon suggested.

Alex Gaynor
As Pär Wieslander pointed out to me when I tried this answer (which I now see I shouldn't have deleted), `catch_warnings()` was introduced in 2.6, so in this case, just having the with statement doesn't help (unless you want to copy the implementation of `catch_warnings()`.
Jon-Eric