Scope actions

W

Will McGugan

Hi,

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?

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


Thanks,

Will McGugan
 
J

Josiah Carlson

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
 
A

Alex Martelli

Will McGugan said:
Alternatively, should I give up this little idiom and use try / finally?

Alas, this is indeed the case. Wish it would be better...


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,459
Latest member
Vida00R129

Latest Threads

Top