bgbg bgbg - 3 months ago 17
Python Question

In Python, how does one catch warnings as if they were exceptions?

A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the

try
except
syntax to properly handle these warnings. Is there a way to do this?

Answer

To quote from the python handbook (27.6.4. Testing Warnings):

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

(edit: fixed example, was a section off)