Specifying `blocking` and `timeout` when acquiring lock as a context manager

Ian Kelly ian.g.kelly at gmail.com
Fri Aug 8 15:21:45 EDT 2014


On Fri, Aug 8, 2014 at 7:25 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 08/08/2014 04:51 AM, cool-RR wrote:
>>
>>
>> If I want to acquire a `threading.Lock` using the context manager
>> protocol,
>>  is it possible to specify the `blocking` and `timeout` arguments that
>>  `acquire` would usually take?
>
>
> Not that I know of, but why would you want to?  There's no built-in 'if'
> with a 'with' block -- how would your code know whether it ran or not?

@contextmanager
def locking(lock, blocking=False, timeout=-1):
  try:
    yield lock.acquire(blocking, timeout)
  finally:
    lock.release()

with locking(lock, timeout=5) as acquired:
  if acquired:
    print('yay!')



More information about the Python-list mailing list