[Python-Dev] With statement
Duncan Booth
duncan@rcp.co.uk
Wed, 5 Feb 2003 10:32:03 +0000
Greg Ewing <greg@cosc.canterbury.ac.nz> wrote in
news:200302050337.h153b4v12977@oma.cosc.canterbury.ac.nz:
>> with lock(my_lock):
>> # protected code
>
> But if my_lock is already a lock object, with appropriate enter
> and leave methods, what would the lock() function do?
>
> If the answer is
>
> def lock(x):
> return x
>
> then I'd say that I don't like the idea of a do-nothing
> function whose purpose is only to make the code look
> pretty.
>
Sorry, I didn't make myself clear. 'lock' here is an adapter class to let
Threading.Lock be used in a with statement. The definition would be:
class lock:
def __init__(self, lockable):
self.lockable = lockable
lockable.acquire()
def __exit__(self):
self.lockable.release()
My point being that the existing proposal with __enter__ and __exit__ may
be replaced by a simpler proposal with only __exit__ by using a class which
does the __enter__ functionality in the constructor.
If the proposal was to change the existing Threading.Lock class so that it
directly supported use in a 'with' statement, then one way would be to add
__enter__ and __exit__ methods. An alternative which doesn't require
__enter__ at all would be to add a single 'lock' method that creates a lock
object as defined above. Then the code might look something like:
my_lock = Threading.Lock()
...
with my_lock.lock():
... protected code ...
--
Duncan Booth duncan@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?