Why does finally make destruction deterministic? What’s the difference between try ... finally: del frame and del frame without finally?
Suppose I have many functions that use frame, and I want to create a decorator to help me avoid having to write del frame every time, something like:
def del_frame(f):
def inner(frame):
try:
return f(frame)
finally:
del frame
return inner
@del_frame
def function_that_uses_frame(frame):
# This function will take a `frame` object from somewhere else.
...
Does it conform to the requirements of frame destruction despite that I didn’t delete the frame inside function_that_uses_frame?
When the code in the try throws an exception or executes a return statement, the frame will still be deleted if coded with finally. If the del is just sequential after the code, it will not be if one of those things occur.
Stack frames are created at call time, so it doesn’t exist yet upon entry into the decorator. Will not work.
If there is no loop, there is no problem. So calling a function with a parameter does not need deleting the reference. The actual parameter is part of the stackframe and will be deleted automatically after the call returns.
In Python the rule of thumb is to not worry about memory until your program starts hogging it.
So as I understand it, as long as we tell the interpreter to break the reference cycle of local variables referenced by frame at some point, it’s fine.