Pre-python 2.6 warning catch

In Python 2.6, you can suppress warnings from the alert module using

with warnings.catch_warnings(): warnings.simplefilter("ignore") fxn() 

Versions of Python prior to version 2.6 do not support with , so I wonder if there are alternatives to the above that will work with versions prior to 2.6?

+7
python warnings suppress-warnings
source share
2 answers

It looks like:

 # 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 try/finally original warning filters will not be restored if fxn () throws an exception. See PEP 343 for a more detailed discussion of how the with statement serves to replace try/finally when used like this.

+3
source share

Depending on which minimum version you should support using Python 2.5

 from __future__ import with_statement 

may be an option, otherwise you may have to drop what John suggested.

-one
source share

All Articles