Destructors and reference counting

Christopher T King squirrel at WPI.EDU
Tue Jul 6 21:36:37 CEST 2004


On 6 Jul 2004, Elbert Lev wrote:

> Please correct me if I'm wrong. 
> Python (as I understand) uses reference counting to determine when to
> delete the object. As soon as the object goes out of the scope it is
> deleted. Python does not use garbage collection (as Java does).

True, except Python uses garbage collection in the sole case of reference 
cycles (which you will likely not encounter).

> 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.
> 
> Is the same true for functions like:
> 
> def A():
>     f1 = Obj(1)
>     f2 = Obj(2)
> 
> Are f1 and f2 deleted before returning from A?

True on all counts.

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

The short answer is, yes, in CPython, for the immediate future, reference 
counting will be used and can be relied upon.

The long answer is, no. It's not guaranteed by the language 
specifications, and it's not used in Jython (where Java's GC is used 
instead).

For a *very* thorough discussion, see the recent thread entitled "python 
has useless destructors?"




More information about the Python-list mailing list