Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

python - __del__ on exit behavior

I have some test.py file:

class A:
    def __init__(self):
        print("A init")

    def __del__(self):
        print("A del")

a = A()

When I run it 10 times (python3 test.py) it always produces next output:

A init
A del

But if I add sys.exit call to end of script:

import sys

class A:
    def __init__(self):
        print("A init")

    def __del__(self):
        print("A del")

a = A()

sys.exit(-1)

in 5 of 10 cases (randomly) i have

A init

and in second half of cases:

A init
A del    

I use Python3.4.3 [MSC v.1600 32 bit] on Windows 7 x64. So why __del__ method called not every time? Do I need to use some other exit method to pass return code of script and have all destructors guaranteed executed? And one more related question: is it possible to execute destructors on receive SIGTERM or SIGKILL from OS?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation:

It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.

If you want to ensure that a.__del__ is invoked, you'll have to explicitly delete the instance:

a = A()
del a   # Assuming this is the final reference to the object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...