10

I have a multithreaded program with a line that causes a warning I want to silence. I don't want to silence warnings anywhere else in the code.

I could do this, as suggested in the docs:

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    line_that_causes_warning()

But the docs also say that it's not thread-safe, because it sets the module-level warning filter.

I realize I could probably solve that with something crazy like protecting this section with a lock, but is there a nice way to make this thread-safe?

1 Answer 1

1

You can do it with threading interface. Lock acquire() method will be called when the with block is started to execution, after the exit of the block release() method will be called.

import warnings
import threading

lock_for_purpose = threading.RLock()
print(lock_for_purpose)
def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with lock_for_purpose:
    print("lock is done")
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        fxn()
1
  • 3
    Thanks for the answer! As I said, I realize locking is possible, but I don't want to protect the function with a lock—I'd want something like contextlib.suppress that doesn't impede multithreading, but for warnings. (I realize that this may not be possible but I could find nothing to confirm it isn't).
    – zale
    May 8, 2019 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.