Search code examples
pythonwarningssuppress-warnings

Catching warnings pre-python 2.6


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?


Solution

  • 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.