question on garbage collection for python

  • Thread starter David Stockwell
  • Start date
D

David Stockwell

Hi,

Does Python leave things in an unknown state?

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 by unallocating the memory (under the hood) and closing the
file.

The questions here are:
If in my code if I forget to close a file, when will the file be closed? Is
it when something goes out of scope? Or will it close when the python
session ends?

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

Thanks in advance,

David

-------
Tracfone: http://cellphone.duneram.com/index.html
Cam: http://www.duneram.com/cam/index.html
Tax: http://www.duneram.com/index.html

_________________________________________________________________
MSN Toolbar provides one-click access to Hotmail from any Web page – FREE
download! http://toolbar.msn.click-url.com/go/onm00200413ave/direct/01/
 
M

Matteo Dell'Amico

David said:
The questions here are:
If in my code if I forget to close a file, when will the file be
closed? Is it when something goes out of scope? Or will it close when
the python session ends?

It isn't specified: it will be collected before the end of the program.
I think that CPython would do it when the refcount goes to 0, whereas in
Jython it will happen "sometimes in the future". Don't count on it, though!
If I define a class of somesort, is there a way I can have a destructor
method (like I would under C++ ?)

The __del__ method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top