import a module in a destructor of a class

Peter Otten __peter__ at web.de
Mon Aug 23 08:41:57 EDT 2010


Navid Parvini wrote:

> I have a python module named "book.py" I want to import it in a destructor
> of a class.

Why would you do that?
 
> class Excel:
> 
> def __init__( self, ... ):
> . . .
> 
> def __del__( self ):
> import book
> 
> but I got error. Would you please help me? Can I import a module in a
> destructor?
> 
> Thank you in advance.

You may be able to avoid the ImportError by moving the instance from the 
global scope into a function, e. g. instead of

e = Excel()
# work with e

do

def main():
    e = Excel()
    # work with e
main()

but the more appropriate answer is likely: Don't use __del__() at all.

Peter





More information about the Python-list mailing list