Question About When Objects Are Destroyed (continued)

Ned Batchelder ned at nedbatchelder.com
Sat Aug 5 18:36:13 EDT 2017


On 8/5/17 5:41 PM, Tim Daneliuk wrote:
> On 08/05/2017 11:16 AM, Ned Batchelder wrote:
>> It uses
>> reference counting, so most objects are reclaimed immediately when their
>> reference count goes to zero, such as at the end of local scopes. 
> Given this code:
>
> class SomeObject:
>     .....
>
>
> for foo in somelist:
>
>    a = SomeObject(foo)
>    b = SomeObject(foo)
>    c = SomeObject(foo)
>
>    # Do something or other
>    ...
>
>    # Bottom of 'for' scope
>
>
> Are you saying that each time a,b,c are reassigned to new instances of
> SomeObject the old instance counts go to 0 and are immediately - as in
> synchronously, right now, on the spot - removed from memory?  
Yes, that is what I am saying.  In CPython, that is.  Other
implementation can behave differently. Jython and IronPython use the
garbage collectors from the JVM and .net, I don't know specifically how
they behave.
> My
> understanding was (and I may well be wrong), that the reference count
> does get decremented - in this case to 0 - but the *detection* of that
> fact does not happen until the gc sweep looks through the heap for such
> stale objects.
That is how classic garbage collectors worked.  And Python has something
like that, but it's only used to collect circular structures, where the
reference counts will never go to zero, but nevertheless the entire
structure can be unreferenced as a whole.

--Ned.



More information about the Python-list mailing list