del behavior 2
Eric Snow
esnow at verio.net
Wed Jan 7 15:03:36 EST 2009
On Jan 7, 12:57 pm, "Chris Rebert" <c... at rebertia.com> wrote:
> On Wed, Jan 7, 2009 at 11:42 AM, Eric Snow <es... at verio.net> wrote:
> > I was reading in the documentation about __del__ and have a couple of
> > questions. Here is what I was looking at:
>
> >http://docs.python.org/reference/datamodel.html#object.__del__
>
> > My second question is about the following:
>
> > "It is not guaranteed that __del__() methods are called for objects
> > that still exist when the interpreter exits."
>
> > I understand that and have seen it too. That's fine. But how do any
> > of you deal with things that are left open because you did not get a
> > chance to close them? How do you clean up after the fact? Do you
> > simply keep track externally the things that need to be cleaned up if
> > __del__ doesn't get a chance? Any ideas? Thanks
>
> As you point out, __del__ is not a reliable way to free limited
> resources. Instead, one generally includes logic to explicitly free
> the resources. This is generally done using try-finally or the `with`
> statement.
>
> Example:
>
> def mess_with_file(f):
> try:
> #fiddle with the file
> finally:
> f.close() #guarantee that the file gets closed
>
> def mess_with_other_file(filename):
> with open(filename) as f:
> #do stuff with file
> x = None #the file has now been closed, and it'll be closed even
> if an exception gets raised
> #the "context handler" (see PEP 343) for the `file` type
> guarantees this for us
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com
Thanks for the responses. What I mean is when a python process is
interrupted and does not get a chance to clean everything up then what
is a good way to do so? For instance, I have a script that uses child
ptys to facilitate ssh connections (I'm using pxssh). When I ^C the
python process I am left with the child processes running and the ssh
connections open. Naturally I run out of ttys if this happens too
much, which I have had happen. So if python does not get a chance to
take care of those, what is a good way to do so? Does a try/finally
or a with statement address that? Thanks!
-eric
More information about the Python-list
mailing list