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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With