using modules in destructors

S

samtygier

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
 
S

samtygier

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.
 
M

MRAB

What would you have different? How would you define the end of a
Python program?  Would all modules and globals remain, and then
darkness?  Would the modules get removed in alphabetical order?
....
I suppose the modules could be removed in the reverse order in which
they were loaded, excepting cross-references (two objects from
different modules referring to their own modules and each other). Even
neglecting modules, if two objects have destructors and refer to each
other, which should be collected first?
 

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,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top