In Python, how does one catch warnings as if they were exceptions?
In Python, how does one catch warnings as if they were exceptions?
To handle warnings as errors simply use this:
import warnings
warnings.filterwarnings(error)
After this you will be able to catch warnings same as errors, e.g. this will work:
try:
some_heavy_calculations()
except RuntimeWarning:
import ipdb; ipdb.set_trace()
P.S. Added this answer because the best answer in comments contains misspelling: filterwarnigns
instead of filterwarnings
.
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)
In Python, how does one catch warnings as if they were exceptions?
If you just want your script to fail on warnings you can invoke python
with the -W
argument:
python -W error foobar.py
Related Posts
- Python – TypeError: int object is not iterable
- python – How do I sort a dictionary by value?
- Does Python have a string contains substring method?
- python – Convert bytes to a string
- What is the Python equivalent for a case/switch statement?
- python – How do I list all files of a directory?
- python – How to copy files?