How to use __del__ in a reliable way?

北城余情 提交于 2019-12-04 06:40:06
Gareth Latty

In short: No, there is no way to ensure it gets called.

The answer is to implement context managers yourself. A with statement roughly translates to:

x.__enter__()
try:
    ...
finally:
    x.__exit__()

So just do it manually. It is a little more complex than that, so I recommend reading PEP 343 to fully understand how context managers work.

One option is to call your cleaning up function close(), and then in future versions of python, people can easily use contextlib.closing to turn it into a real context manager.

Instead of __del__, give your class a method called something like close, then call that explicitly:

foo = Foo()
try:
    foo.do_interesting_stuff()
finally:
    foo.close()

For extra safety and forward-compatibility, have __exit__ and __del__ call close as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!