Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python locally suppress warnings in thread-safe way

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?

like image 403
zale Avatar asked Nov 07 '22 17:11

zale


1 Answers

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()
like image 70
Erçin Akçay Avatar answered Nov 15 '22 11:11

Erçin Akçay