In my python program, I create a self-defined object. This program is exited by receiving a CTRL-C signal. However, the __del__
function is not called when the program exits. When the program exits, all the object created by this program should be deleted, but why the __del__
function is not called? For now, in order to do some clean-up, i resolve to atexit
module. Is there any more graceful methods?
Actually, I want to use RAII in C++
to manage my python object, can I do this?
Asked
Active
Viewed 979 times
-2

王璘钰
- 25
- 2
-
Atexit is quite graceful for this purpose. Have you tried any other form of research? – Mad Physicist Aug 14 '18 at 03:20
-
4`__del__` [is not guaranteed to be called, ever, unless you execute the operator `del`](https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it), and should not be used. – DYZ Aug 14 '18 at 03:20
-
1I am bothered to learn about this. Destructors should matter, like, to gracefully close handlers, save state to permanent storage or notify peers that the server is closing, or a general purpose async trigger of events. It seems the Python creators really don't care about proper memory management. – Havenard Aug 14 '18 at 03:34
-
Actually, I just don't understand why object will not be deleted when the python program exits – 王璘钰 Aug 14 '18 at 03:35
-
1@Havenard There are mechanisms for that, just not `__del__`. – tripleee Aug 14 '18 at 03:39
-
@tripleee Well I'm sure there are several options to achieve virtually anything when it comes to programming. – Havenard Aug 14 '18 at 03:43
-
2@Havenard: It’s usually inappropriate to link important behaviour like you describe to destructors in languages with garbage collection where they’re called at indeterminate times. The behaviour and correct replacement (usually context managers) are the same in, for example, .NET (`IDisposable` + `using`) and Java (`AutoCloseable` + try-with-resources): be explicit about lifetimes of non-GC resources. – Ry- Aug 14 '18 at 03:45
-
Is there any way to use `RAII in C++` in python? – 王璘钰 Aug 14 '18 at 03:47
-
`__del__` should arguably have been renamed to something less ... seductive in Python 3. – tripleee Aug 14 '18 at 03:51
1 Answers
5
Use the atexit
module:
import atexit
atexit.register(your_function_name)
or, in your case:
import atexit
atexit.register(__del__)

Tono
- 181
- 1
- 5