using modules in destructors

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • samtygier@gmail.com

    using modules in destructors

    Hi

    i have i have a class that makes temp folders to do work in. it keeps
    track of them, so that in the __del__() it can clean them up. ideally
    if the user of the module still has objects left at the end of their
    program, they should be automatically cleaned up. in my destructor i
    had a call to shutil.rmtree (which had been imported at the start of
    more module), however when the destructor is called shutil has been
    set to None.

    i have made a minimal case to reproduce

    #!/usr/bin/env python
    import shutil
    from math import *

    class Foo(object):
    def __init__(self):
    print shutil
    def __del__(self):
    print shutil

    if __name__ == '__main__':
    print shutil
    a = Foo()

    this outputs
    <module 'shutil' from '/usr/lib/python2.5/shutil.pyc'>
    <module 'shutil' from '/usr/lib/python2.5/shutil.pyc'>
    None

    the odd thing is that if i remove the line "from math import *" then i
    get the output
    <module 'shutil' from '/usr/lib/python2.5/shutil.pyc'>
    <module 'shutil' from '/usr/lib/python2.5/shutil.pyc'>
    <module 'shutil' from '/usr/lib/python2.5/shutil.pyc'>

    This seems inconsistent, and makes me wonder if it is a bug in the
    interpreter.

    As an ugly work around i have found that i can keep a reference to
    shutil in the class.

    class Foo(object):
    def __init__(self):
    self.shutil = shutil
    print self.shutil
    def __del__(self):
    print shutil
    print self.shutil

    But given the difference an import statement can make, i am not sure
    this is robust.

    I have been working with Python 2.5.2 (r252:60911, Oct 5 2008,
    19:24:49) from ubuntu intrepid.

    (if google groups does bad things to the code formating, please see
    http://ubuntuforums.org/showthread.php?p=6024623 )

    Thanks

    Sam
  • Michele Simionato

    #2
    Re: using modules in destructors

    This is expected behavior (see http://www.python.org/doc/essays/cleanup)
    but it is definitely a wart of Python. The best advice I can give you
    is *never* use __del__. There are alternatives,
    such as the with statement, weak references or atexit.
    See for instance http://code.activestate.com/recipes/523007/
    If you Google in this newsgroup for __del__ you will find a lot of
    discussion.

    Michele Simionato

    Comment

    • samtygier@gmail.com

      #3
      Re: using modules in destructors

      It seems to me that deleting local instances before imported modules
      would solve the problem. Is it not possible for the interpreter to get
      this right? Or are there cases where this would break stuff.

      It seems rather unpythonic for the __del__() method to become
      unpredictable at exit.

      Comment

      Working...