Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Is there a shutdown equivalent to __init__ ()

Tags:

python

I use __init__() functions a lot in Python classes to set up things when a class is first called.

Is there an equivalent function that is called when a script is shutting down?

like image 484
KermitG Avatar asked Sep 22 '26 01:09

KermitG


1 Answers

There is the __del__ method which is called when an object is finalized. However, python doesn't guarantee that __del__ will actually be called on objects when the interpreter exits.

There are a few alternatives:

  • atexit.register -- Here you can register a function to run when your script terminates
  • create a context manager and use the with statement. Then your context manager's __exit__ method will be called unconditionally when you leave the context.

both of these options would fail if you did something really nasty to exit your program (e.g. somehow causing a segmentation fault or exiting via os._exit)

like image 177
mgilson Avatar answered Sep 25 '26 16:09

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!