0

I am new to Python, I want to understand more the purpose of the __delete__ method.

In my case I got a class that opens a file and I want to add file.close in __delete__ method. Would you consider this as a good idea? Or does the __delete__ is used in a different way?

From the docs I am not sure that am using it right. http://python-reference.readthedocs.io/en/latest/docs/dunderdsc/delete.html

5
  • 3
    __delete__ is one of the descriptor methods. Perhaps you want __del__? Commented Jun 19, 2017 at 21:18
  • @vaultah I added a link to the doc. Once again I am new in Python so I just want to do understand what delete does. What del is? Commented Jun 19, 2017 at 21:22
  • 1
    __delete__ is part of the descriptor protocol. Are you writing a descriptor? Commented Jun 19, 2017 at 21:23
  • 2
    Almost certainly you should not be messing with __del__, if that is indeed what you mean. You probably want a context manager. Commented Jun 19, 2017 at 21:23
  • ...in which case it's __exit__, not either __del__ or __delete__. Commented Jun 19, 2017 at 21:28

1 Answer 1

2

The rule of thumb: if you want to use a destructor for resource management, don't. It's unpredictable and unreliable.

Your options:

  • Use a context manager (see contextlib) to deterministically free resources when a scope ends.
  • Use a behind-the-scenes list of weak references to resources and an exit hook; works for most cases of program termination.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.