Destructors and reference counting

Terry Reedy tjreedy at udel.edu
Tue Jul 6 18:15:40 EDT 2004


"Elbert Lev" <elbertlev at hotmail.com> wrote in message
news:9418be08.0407061111.2ca74e73 at posting.google.com...
> Please correct me if I'm wrong.

Ok. This is a good way to learn...

> Python (as I understand) uses reference counting to determine when to
> delete the object.

The Python definition intentionally does not specify memory management.
The CPython implementation does use reference counting as its primary
method.

>  As soon as the object goes out of the scope it is deleted.

When there are no references to an object, it *may* be deleted.  In
CPython, when the reference count does reach 0, it is deleted.  'Scope' is
a bit vague in the Python context.

> Python does not use garbage collection (as Java does).

CPython uses generational gc to collect unreachable objects whose ref
counts remain above 0 due to reference cycles.  Jython uses Java's native
gc for all memory reclamation.  For human rather than computer
interpreters, memory management is probably completely different.  There
are other computer implementations and compilers that I cannot speak about
in this regard.

> So if the script runs a loop:
>
> for i in range(100):
>     f = Obj(i)
>
> Every time f = Obj(i) is executed it is preceded by f.__del__() call.

No.  What happens *in CPython* when a name is bound is that if it was
previously bound to something else, the ref count of that something else is
decreased by 1.  If that decrease decreases the ref count of that object to
0, then yes, the object is deleted.

> Is the same true for functions like:
>
> def A():
>     f1 = Obj(1)
>     f2 = Obj(2)
>
> Are f1 and f2 deleted before returning from A?

When a function returns, local names are unbound from the objects they are
bound to.  In CPython, this means the same as above (decrement and delete
if 0).

> If my assumptions are correct,  tell me please: can I expect that no
> garbage collection will be used in the future

As I already said, it already is used in both the main computer
implementations

> and Python will use reference counting?

CPython (again, not Python) uses ref counting today because efforts some
years ago to replace it with 'true' gc failed to produce better binaries.
It seems that the episodic gc overhead was, averaged over time, about as
high as the constant overhead of ref counting.  As long as running speed is
roughly even, the plus of r.c. predictability will continue to tip the
decision in its favor.  I know of no efforts today to change the current
status.

Terry J. Reedy






More information about the Python-list mailing list