I am trying to figure out when exactly a python object is a candidate for garbage collection. I have read through a few documents/posts and have been unable to find a definite answer.
Take for example the following line. This is the last reference to foo. When is the object pointed to by foo available for garbage collection?
ret = func(['xyz: ' + foo.name])
Breaking it down to the (possible) individual steps:
- temporary reference to name is created.
- ‘xyz: ‘ is concatenated with name and value is returned.
- list is created with the new string.
- function is called with new array.
- function returns.
- result is assigned to ret.
- next instruction…
Between which two steps is the object first eligible to be collected? When is the reference count to the object decremented?
If the list of steps is incomplete/incorrect please let me know as well. I only attempted to enumerate them to give a common starting place for the potential answers to reference.
The variable will be eligible for garbage collection as soon as all references to it go out of scope or are manually deleted (
del x).In your example,
foomust exist before this line (otherwise it’s aNameError), and therefore will never be garbage collected in your example block of code, as the reference will still exist after this. Even if one were to calldel fooafter this, we would have to presume there were no references to the object anywhere else for it to be garbage collected.