using modules in destructors

samtygier at gmail.com samtygier at gmail.com
Fri Oct 24 09:45:16 EDT 2008


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



More information about the Python-list mailing list