dumping in destructor

robert no-spam at no-spam.invalid
Mon Oct 20 05:25:13 EDT 2008


Митя wrote:
> I have a class which I want to save it's data automatically on disc,
> when it's destroyed. I have following code:
> 
> from cPickle import dump
> 
> class __Register(object):
>     def __init__(self):
>         self.dict = {}
>     def __del__(self):
>         fh = open('aaa', 'w')
>         dump(self.dict, fh)
>         fh.close()
> 
> g_register = __Register() # global instance. I do not destroy it
> manually, so destructor is called on iterpreter exit
> 
> But when g_register is being destroyed, dump seems to be already dead,
> so I get:
> 
> Exception exceptions.TypeError: "'NoneType' object is not callable" in
> <bound method __Register.__del__ of <MyWiki.Register.__Register object
> at 0x835a74c>> ignored
> 
> can I somehow save my data from destructor?


the order of __del__ execution is quite unreliable (depending on 
implementation/version of Python).
Also there is problematic/circular garbage (gc.garbage).

=>

1. For algorithmic use cases see 'with' statement 
http://python.about.com/od/gettingstarted/qt/py25WITH.htm


2. For data structure trees implement your own register/deregister 
book-keeping. Often a kind of "second" container-refcount 
attribute does it at core in cases with multiple but non-circular 
linking.
Yet, to get the effect in a cheap way, one can often do something 
like this:
Add those objects also to a global container

g_reg_containter.add( myObject )

Then periodically and at critical times (and maybe finally 
sys.exitfunc) after gc.collect() check the sys.getrefcount(obj) 
(or the "second" refcount) to fall below "1 plus number of extra 
local refs". In case execute your  obj.__deregister()  or so ...


Robert




More information about the Python-list mailing list