Ilya Gazman
Ilya Gazman

Reputation: 32221

Python: What should go in __delete__ method

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

Upvotes: 0

Views: 100

Answers (1)

9000
9000

Reputation: 40884

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.

Upvotes: 2

Related Questions