Python how to ensure that __del__() method of an object is called before the module dies? -



Python how to ensure that __del__() method of an object is called before the module dies? -

earlier today asked this question __del__() method of object uses imported module. problem __del__() wants create utilize of module os, (not always) module has been deleted. told when python programme terminates, order in objects , modules deleted can random, , undefined. however, application, need create sure object (instance of class created) gets deleted before module (in object instantiated) gets deleted. there way of doing this?

as told before, shouldn't rely on __del__ beingness called when interpreter exits. there 2 options doing properly:

the first atexit

import os class logger(object): def del(self): print "os: %s." % os logger = logger() atexit.register(logger.del)

this makes sure logger gets finalized @ exit.

*reading little more problem, since plan on having single instance bound module defines instances's class, context manager solution below won't work since there's no way remain in context entire execution of program. you'll need utilize atexit.register. however, standpoint of programme design, much prefer utilize context manager manage resources atexit.register if restructuring code allow it.

the sec (better*) way create class context manager executes cleanup code when exit context. code like:

import os class logger(object): def __enter__(self): homecoming self def __exit__(self, exc_type, exc_value, traceback): print "os:",str(os) logger() logger: #do ...

python module destructor

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -