Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore exceptions printed to stderr in __del__()

Tags:

python

According to the Python (2.7) documentation:

Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead

What would be the most Pythonic way to completely and absolutely ignore an exception raised in __del__() — that is, not only having the exception ignored but also nothing printed to sterr. Is there a better way than temporarily redirecting stderr to the null device?

like image 804
plok Avatar asked Dec 15 '22 16:12

plok


1 Answers

I am assuming this is in a __del__() function that you are writing, if so, just catch the exception yourself and ignore it.

def __del__(self):
    try:
        # do whatever you need to here
    except Exception:
        pass

The logging to stderr only applies for uncaught exceptions in __del__().

like image 146
Andrew Clark Avatar answered Dec 21 '22 10:12

Andrew Clark