classification
Title: [contextlib] Reverse order of locking
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.0, Python 2.6
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: DragonSA, benjamin.peterson
Priority: normal Keywords:

Created on 2008-09-24 15:01 by DragonSA, last changed 2010-04-29 17:43 by terry.reedy. This issue is now closed.

Messages (3)
msg73715 - (view) Author: David Naylor (DragonSA) * Date: 2008-09-24 15:01
Overview:
Add a generator that will revert the order applied to a with 
statement.  

Motivation:
Often with threaded applications one needs to do a certain task 
outside of a lock but while inside a greater block of code protected 
by a lock.  

e.g:
with lock:
  BLOCK1
  lock.release()
  try:
    BLOCK2
  finally:
    lock.acquire()
  BLOCK3

but with an inverter for a with statement it becomes:

with lock:
  BLOCK1
  with invert(lock):
    BLOCK2
  BLOCK3

[Of course there are many other possible uses for this...]

Implementation:
def invert(thing):
  thing.__exit__(None, None, None)
  yield thing
  thing.__enter__()

Issues:
Normal exception handling will not take place (however for locks and 
the like this is not an issue)
msg73716 - (view) Author: David Naylor (DragonSA) * Date: 2008-09-24 15:03
Apologies, obviously the invert function should be preceded by an 
@contextmanager to become:

@contextmanager
def invert(thing):
  thing.__exit__(None, None, None)
  yield thing
  thing.__enter__()

[Although there may be a better way of doing this, perhaps as a 
class?]
msg73759 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2008-09-24 22:15
This doesn't sound like such a good idea. In the example you gave, it is
trivial and easier to use two separate with statements than three!
History
Date User Action Args
2010-04-29 17:43:54terry.reedysetstatus: pending -> closed
2008-09-24 22:15:54benjamin.petersonsetstatus: open -> pending
resolution: rejected
messages: + msg73759
nosy: + benjamin.peterson
2008-09-24 15:03:17DragonSAsetmessages: + msg73716
2008-09-24 15:01:02DragonSAcreate