TIL

Suppressing Python Warnings Locally

Python's warnings.catch_warnings() context manager allows warning suppression scoped to a specific block of code. 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.0