bgbg bgbg - 6 months ago 39
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

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


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.
    # Trigger a warning.
    # 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)