Python: flush buffer before program termination through finalizer

I save the transaction cache for cleaning (in persistent storage) in case of completion of the watermark or object. Since it is __del__ no longer guaranteed to be called on every object, is there a suitable approach for binding a similar function (or itself __del__) to atexit.register(during initialization)?

If I'm not mistaken, this will call the object to which the method is bound to hang until the program terminates. This is unlikely to be a problem, but maybe there is a more elegant solution?

Note. I know that use __del__is imperfect because it can cause fuzzy exceptions , but I can’t think of another way to do this except for cascading finalize()calls all the way through my program. TIA!

+3
source share
5 answers

If you don’t need your object to be alive while you are doing flash, you can use weak links

, , , , . , , __del__.

, , .

+2

ressources, close() finalize(). with, . weakref. , , __del__(), , .

+4

atexit , , with_statement, __future__ 2.5 2.6. 2.5 contextlib . - Canonical Storm ORM.

import with_statement

@contextlib.contextmanager
def start_transaction(db):
  db.start()
  yield
  db.end()

with start_transaction(db) as transaction:
  ...

, db, , , - . , .

+3

destructor.py

:
import atexit

objects = []

def _destructor():
    global objects
    for obj in objects:
        obj.destroy()
    del objects

atexit.register(_destructor)

now use it as follows:

import destructor

class MyObj(object):
    def __init__(self):
        destructor.objects.append(self)
        # ... other init stuff
    def destroy(self):
        # clean up resources here
+2
source

I think that atexitis the way here.

0
source

All Articles