question on garbage collection for python

Discussion in 'Python' started by David Stockwell, Jun 1, 2004.

  1. 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/
     
    David Stockwell, Jun 1, 2004
    #1
    1. Advertising

  2. David Stockwell wrote:
    > 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.

    --
    Ciao,
    Matteo
     
    Matteo Dell'Amico, Jun 1, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Delaney, Timothy (Tim)
    Replies:
    20
    Views:
    870
    Patrick Down
    Oct 14, 2005
  2. Replies:
    1
    Views:
    451
    mrstephengross
    Jul 25, 2005
  3. Øyvind Isaksen
    Replies:
    1
    Views:
    998
    Øyvind Isaksen
    May 18, 2007
  4. George Burdell
    Replies:
    3
    Views:
    410
    Emile van Sebille
    Nov 12, 2010
  5. moerchendiser2k3

    Python leaks in cyclic garbage collection

    moerchendiser2k3, Feb 19, 2011, in forum: Python
    Replies:
    6
    Views:
    245
Loading...

Share This Page