"RuntimeWarning: invalid value encountered" flooding logs — how to scope np.seterr without global side effects
26.5K reputation · 20 Mar 2026, 00:31 UTC
A numerical pipeline built on NumPy (assume a recent 1.26/2.x release) emits repeated RuntimeWarning: invalid value encountered in ... messages from a handful of known-benign operations, such as 0/0 ratios in masked aggregations. The goal is to keep genuinely useful alerts for unexpected nan/inf propagation while silencing the expected cases, so real problems are not lost in notification noise.
The documented knobs are np.seterr with the four conditions (divide, over, under, invalid) and the scoped np.errstate context manager. The uncertainty is the right split: failing fast with invalid='raise' is attractive for catching bugs early, but seterr mutates process-wide (thread-local) state, which is risky in library code consumed by other packages. Raising on under also seems undesirable, since underflow to zero is usually harmless.
Specifically:
- Is wrapping only the numerically sensitive sections in
np.errstate(invalid='raise'), pluserrstate(invalid='ignore')around the known-benign 0/0 sites, the intended pattern, or is a globalseterrconfiguration acceptable for an application (not a library)? - Since warnings fire once per ufunc call rather than per element, is there a documented way to locate which inputs produced the
nanwithout a separatenp.isnanaudit pass? - Do these settings behave differently for integer division/overflow, which should be verified separately?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 20 Mar 2026, 03:53 UTC
NumPy’s error mode is stored per‑thread, so np.seterr changes the setting only for the thread that calls it. In a single‑threaded script this looks global, but in multi‑threaded code or when a library is called from another thread the change does not leak to other threads. Nevertheless, because a library cannot control which thread will execute its code, it is still safer to use np.errstate as a context manager.
Integer arithmetic (e.g., np.divide on int32 arrays) does not trigger the floating‑point error flags; a division by zero raises a Python ZeroDivisionError or returns the platform‑defined integer result, so np.seterr settings for divide, invalid, over or under have no effect. If you need to catch integer overflow you must rely on NumPy’s casting rules or explicit checks.
To locate which array elements produced a nan after an operation, NumPy does not provide per‑element warning metadata. The usual pattern is to compute the result, then use np.where(np.isnan(result)) (or np.argwhere) to obtain the indices. This check is cheap compared to the ufunc call and avoids the need for a separate audit pass.