Skip to content

Instantly share code, notes, and snippets.

@mborus
Created August 2, 2017 08:06
Show Gist options
  • Save mborus/e14fd2daabe556c00c65adf6105db8a2 to your computer and use it in GitHub Desktop.
Save mborus/e14fd2daabe556c00c65adf6105db8a2 to your computer and use it in GitHub Desktop.
Conditional "with" context manager
"""
Python3 conditional locking example
"""
from threading import Lock
lock = Lock()
class ConditionalLock(object):
"""silly example to test locking via context manager"""
def __init__(self, lockrequest=True, verbose=False):
self.lockrequest = lockrequest
self.verbose = verbose
def __enter__(self):
if self.lockrequest:
if self.verbose:
print("I'd better be locking, then.")
lock.acquire()
if self.verbose:
print("Success: Lock acquired!")
else:
if self.verbose:
print("I will do no locking")
def __exit__(self, exc_type, exc_value, traceback):
if self.lockrequest:
if self.verbose:
print("Unlocking attempt in progress.")
lock.release()
if self.verbose:
print("Success. The lock is history.")
else:
if self.verbose:
print("No need to do any unlocking")
if __name__ == '__main__':
with ConditionalLock(lockrequest=False, verbose=True):
print('I am working!')
with ConditionalLock(lockrequest=True, verbose=True):
print('I am working with a lock!')
try:
raise RuntimeError('Ooops!')
except RuntimeError as e:
print('I think I saw a runtime error')
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment