Created
October 13, 2010 18:27
-
-
Save mattvonrocketstein/624587 to your computer and use it in GitHub Desktop.
hacky decorators for defeating annoying race conditions
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
| """ some decorator hacks for defeating annoying race conditions """ | |
| def when(predicate, limit=100, sleep_time=1, eager=False): | |
| """ this function is dedicated to Christopher Michael Heisel | |
| When predicate is True, the decorated function will run | |
| (and nevermind exactly when it was called). If the predicate | |
| tests False for more times than <limit>, this function will | |
| simply exit and the decorated function will never be called. | |
| NOTE: you still need to call your function, unless eager=True | |
| Example usage: | |
| @when(lambda: AppCache().app_cache_ready()) | |
| def do_patch(): | |
| trivialize_method('ellington.alerts.tests.lists', | |
| 'AlertListsTestCase', | |
| 'test_admin_2_subs') | |
| do_patch() | |
| """ | |
| def wrapper(func): | |
| def inner(*args, **kargs): | |
| def real_one(): | |
| count = 0 | |
| while True: | |
| count+=1 | |
| time.sleep(sleep_time) | |
| if predicate(): break | |
| if count>limit: break | |
| if count<limit: | |
| func(*args, **kargs) | |
| threading.Thread(target=real_one).start() | |
| if eager: inner() | |
| return inner | |
| return wrapper | |
| def do_when(predicate, **kargs): | |
| """ shortcut: like when(), except always eager """ | |
| return when(predicate,eager=True,**kargs) | |
| def do_when_appcache_ready(**kargs): | |
| """ shortcut: like do_when, except predicate is implied """ | |
| predicate = lambda: AppCache().app_cache_ready() | |
| return do_when(predicate,**kargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment