[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Question About When Objects Are Destroyed (continued)

On 2017-08-05 22:41, 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?  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.
After this:

     a = SomeObject(foo)

the name "a" is bound to an instance of SomeObject and the reference 
count of that instance is 1.

If you then bind "a" to something else:

     a = None

the reference count of the instance is decremented to 0, at which point 
the instance is reclaimed.

The GC sweep stuff is for handling cycles where an object is unreachable 
but its reference count is non-zero.