Skip to content

Instantly share code, notes, and snippets.

@arouene
Created August 27, 2018 07:37
Show Gist options
  • Save arouene/e034a123c6284482e950ab51cb9607fb to your computer and use it in GitHub Desktop.
Save arouene/e034a123c6284482e950ab51cb9607fb to your computer and use it in GitHub Desktop.
Python decorator for exclusive methods
def one_at_a_time(message):
''' Decorator for exclusive methods
Using like this:
@one_at_a_time("Deployment or build already running")
def deploy(self, msg, args)
'''
def mutex_decorator(func):
@wraps(func)
def wraper(self, *args, **kwargs):
if not mutex.locked():
# Not locked, call the function
try:
mutex.acquire()
# return a generator if calling a generator
if inspect.isgeneratorfunction(func):
for res in func(self, *args, **kwargs):
yield res
else:
yield func(self, *args, **kwargs)
finally:
mutex.release()
else:
# Locked, fire a message
yield message
return wraper
return mutex_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment