Questions about explicitly deleting Python frames

Reposted my SO question here.

I found this paragraph in Python’s documentaton:

enter image description here

I have a few questions:

  1. Why does finally make destruction deterministic? What’s the difference between try ... finally: del frame and del frame without finally?

  2. 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?

  1. 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.
  2. Stack frames are created at call time, so it doesn’t exist yet upon entry into the decorator. Will not work.

Thanks Menno. For question 2, to clarify, the frame is not the call frame of function_that_uses_frame, it’s from somewhere else.

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.

1 Like

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.

Never mind. I misunderstood the documentation.