Reputation: 18863
The documentation says:
Note Keeping references to frame objects, as found in the first element of the frame records these functions return, can cause your program to create reference cycles. Once a reference cycle has been created, the lifespan of all objects which can be accessed from the objects which form the cycle can become much longer even if Python’s optional cycle detector is enabled. If such cycles must be created, it is important to ensure they are explicitly broken to avoid the delayed destruction of objects and increased memory consumption which occurs.
Though the cycle detector will catch these, destruction of the frames (and local variables) can be made deterministic by removing the cycle in a
finally
clause. This is also important if the cycle detector was disabled when Python was compiled or usinggc.disable()
. For example:def handle_stackframe_without_leak(): frame = inspect.currentframe() try: # do something with the frame finally: del frame
If you want to keep the frame around (for example to print a traceback later), you can also break reference cycles by using the
frame.clear()
method.
Which supposedly means that there are two things that have references to each other. What are they exactly?
Can you explain more precisely under which conditions a reference cycle is created? When I do inspect.currentframe()
without del frame
? Does the same go for inspect.stack()
? Any other methods/circumstances?
Upvotes: 3
Views: 136