February 11, 2026
Scoped Warning Suppression in Python
Python’s warnings module supports scoped suppression, allowing specific warnings to be silenced in a targeted block of code without affecting the rest of the application.
The warnings.catch_warnings() context manager temporarily overrides the active warning filters. Any filters added inside the block are discarded when it exits:
import warnings
import numpy as np
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="divide by zero",
category=RuntimeWarning,
)
ratios = np.log(old_values / new_values)
ratios[~np.isfinite(ratios)] = 0.0Targeted Filtering
Filters can be as broad or narrow as needed. The message parameter accepts a regex matched against the warning text, and category restricts it to a specific warning class. Both are optional — omitting them will match more broadly.
For cases where granularity isn’t important, simplefilter is a shorthand:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
noisy_third_party_call()Escalating to Errors
You can also use this pattern to strictly enforce zero warnings, which is useful in CI/CD environments or test suites:
with warnings.catch_warnings():
# Turn all warnings into exceptions
warnings.simplefilter("error")
# This will now raise a RuntimeWarning exception
call_deprecated_function()Capturing Warnings
If you need to verify that a warning is issued (e.g., in unit tests), use record=True to capture them into a list instead of printing them:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always") # Cause all warnings to always be triggered
trigger_warning()
assert len(w) == 1
assert issubclass(w[-1].category, RuntimeWarning)
assert "invalid value" in str(w[-1].message)