Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 22nd, 2012  |  syntax: None  |  size: 0.91 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. In python, how does one catch warnings as if they were exceptions?
  2. import warnings
  3.  
  4. def fxn():
  5.     warnings.warn("deprecated", DeprecationWarning)
  6.  
  7. with warnings.catch_warnings(record=True) as w:
  8.     # Cause all warnings to always be triggered.
  9.     warnings.simplefilter("always")
  10.     # Trigger a warning.
  11.     fxn()
  12.     # Verify some things
  13.     assert len(w) == 1
  14.     assert issubclass(w[-1].category, DeprecationWarning)
  15.     assert "deprecated" in str(w[-1].message)
  16.        
  17. import warnings
  18. with warnings.catch_warnings(record=True) as w:
  19.     # Cause all warnings to always be triggered.
  20.     warnings.simplefilter("always")
  21.  
  22.     # Call some code that triggers a custom warning.
  23.     functionThatRaisesWarning()
  24.  
  25.     # ignore any non-custom warnings that may be in the list
  26.     w = filter(lambda i: issubclass(i.category, UserWarning), w)
  27.  
  28.     if len(w):
  29.         # do something with the first warning
  30.         email_admins(w[0].message)