views:

27

answers:

2
class A(object):
    def __init__(self):
        self.db = create_db_object()

    def change_Db_a(self):
         self.db.change_something()
         self.db.save()

    def change_db_b(self):
         self.db.change_anotherthing()
         self.db.save()

I am getting object from database, I changing it in multiple function and saving it back. which is slow because it hits database on every function call. is there anything like deconstructor where I can save the database object so that I don't have to save it for every function call and not waste time.

+1  A: 

You can define a del method.

def __del__(self):
    self.db.save()

But note that this violates data consistency.

pifantastic
Thanks. That's what I wanted. One more question : How to detect change in db ? so that , If nothing changed, I do not unnecessarily save object to database on every del.
iamgopal
You can overload `__setattr__` in your class and set flag on its call. Then check that flag at `__del__`.
Daniel Kluev
+3  A: 

Don't rely on the __del__ method for saving your object. For details, see this blog post.

You can use use the context management protocol by defining __enter__ and __exit__ methods:

class A(object):
    def __enter__(self):
        print 'enter'
        # create database object here (or in __init__)
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        print 'exit'
        # save database object here

    # other methods

Then use the with statement when you create your object:

with A() as myobj:
    print 'inside with block'
    myobj.do_something()

When you enter the with block, the A.__enter__ method will be called. When you exit the with block the __exit__ method will be called. For example, with the code above you should see the following output:

enter

inside with block

exit

Here's more information on the with statement:

ars
It gives me error that , AttributeError: 'A' object has no attribute 'db'
iamgopal
Hard to say since I can't see your code (there's no `db` in the code I wrote above). But are you sure you initialized your `db` variable? Are you missing the `self`? Sounds like a different problem though, so maybe you should start a new question and post some code.
ars