Search code examples
pythonwarningssuppress-warnings

Python: why is warning printed twice following temporary suppression?


It seems that temporarily suppressing warnings makes repeat warnings outside of the context manager display repeatedly.

Example:

import warnings

def f():

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=Warning)
        print("A")

    print("B")
    warnings.warn("My warning")


f()
f()

Output:

A
B
tmp2.py:10: UserWarning: My warning
  warnings.warn("My warning")
A
B
tmp2.py:10: UserWarning: My warning
  warnings.warn("My warning")

Also, it does not seem to matter what action and category I give to simplefilter.

On the other hand, if I comment out the context catch_warnings block, then the warning only displays once (as intended).

Why? Is it a bug? What am I missing?


Solution

  • This is a known bug also asked about here with a PR that seems pretty stale