I want to know when the Obj.del() method
is going to be called.
def my_integers():
Obj = ExitObj()
i = 0
while(1):
yield i
i += 1
def test_fun():
for i in my_integers():
if i > 3:
break
anything_function()
test_fun()
I did a test and Obj appeared to be deleted just after the break statement: before the anything_function() out the loop.
Can I rely on this and give some tasks that I want to be done when the loop is left to the __ del__ method of the object defined inside the generator?
You can’t. It might never. Finalizers in Python (or in any environment with an automated garbage collector scheme, really) are not guaranteed to run at all, and should only be used for last-resort cleanup. If you want predictable lifetime management, use
withstatement and context managers.