Scope actions

Josiah Carlson jcarlson at uci.edu
Sat Oct 9 19:40:08 CEST 2004


 
> I often write small classes in C++ the use the side effects of scope. 
> For example a CAutoLock class that locks a mutex in the constructor and 
> releases it in the destructor. Is this something that is easily 
> accomplished in Python? I'm guessing that using __init__ and __del__ 
> would be roughly equivalent to this. But can can I be sure - with 
> garbage collection - that __del__ is called immediately at the point of 
> going out of scope?

From what I have come to experience, adding a __del__ method is an
almost sure way of guaranteeing that the object will never be garbage
collected.  This may not be the case in general, but every thing I've
tried to use it on has resulted in a memory leak; an infinitely growing
gc.garbage .

If you must do that kind of thing, play a bit with weakref objects.  You
can make them work the way you want them to.


> Alternatively, should I give up this little idiom and use try / finally?

I would make that suggestion.  It isn't so bad to:

class foo:
    def __init__(self):
        self.lock = threading.Lock()
    def accessor(self):
        try:
            self.lock.acquire()
            #do work here
        finally:
            self.lock.release()


 - Josiah




More information about the Python-list mailing list