question on garbage collection for python

Terry Reedy tjreedy at udel.edu
Tue Jun 1 10:37:05 EDT 2004


"David Stockwell" <winexpert at hotmail.com> wrote in message
news:BAY2-F108yo5EjEJi9D0002dfdb at hotmail.com...
> Does Python leave things in an unknown state?

If you include internal, system-dependent vars in 'state', yes.

> say I do this in my python code
> someFile = open('somefile' , 'r')
> data = someFile.read()
> someFile = 3
>
> At this point I would hope python would know to destruct the prior
reference
> to someFile

Rebinding the name 'someFile' to another object does that

> by unallocating the memory (under the hood) and closing the file.

When the last reference to an object disappears, (as happens above to the
file object previously bound to 'someFile'), the interpreter *may* do some
implementation-defined 'clean-up action'.

> The questions here are:
> If in my code if I forget to close a file, when will the file be closed?

In current reference-counted CPython, immediately upon reference count
dropping to 0.  In garbage-collected-only Jython, whenever.  It is
controversial (Ie, discussed on several previous threads without agreement)
whether or not it is 'legitimate' to depend on the current CPython
behavior.

>  Is it when something goes out of scope?

As far as I know, going out of scope is no different from explicit deletion
of the binding or implicit deletion by rebinding.

>  Or will it close when the python session ends?

CPython make some effort to cleanup without crashing.  You can register
your own onexit function.  You can find more discussion in past threads
(archives/Google).

> If I define a class of somesort, is there a way I can have a destructor
> method (like I would under C++ ?)

Yes: __del__(self) - but be careful.  1). The time of it being called is
still implementation dependent as described above for closing.  2). For
CPython (don't know about Jython), presence of such a methods disables
cyclic garbage collecion for instances of such a class because collector
cannot know which del to call first and because calling Python-coded dels
in middle of internal C-coded gc code too easily puts system in unstable
state.

> Thanks in advance,

See archives/Google for more.

Terry J. Reedy







More information about the Python-list mailing list