dumping in destructor

Hrvoje Niksic hniksic at xemacs.org
Mon Oct 20 11:40:34 CEST 2008


Митя <netimen at gmail.com> writes:

> 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

In that case you'd be better off using something like:

import atexit
...
g_register = __Register()
atexit.register(g_register.save)

'save' being a method that dumps the instance to the file.



More information about the Python-list mailing list