Created
August 27, 2018 07:37
-
-
Save arouene/e034a123c6284482e950ab51cb9607fb to your computer and use it in GitHub Desktop.
Python decorator for exclusive methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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