Created
October 14, 2013 02:29
-
-
Save beanyoung/6969790 to your computer and use it in GitHub Desktop.
A proxy that ensures only one method of class is running.
This file contains 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
from functools import wraps | |
import threading | |
import types | |
lock = threading.Lock() | |
def method_lock(f): | |
@wraps(f) | |
def decorator(*args, **kwargs): | |
lock.acquire() | |
try: | |
return f(*args, **kwargs) | |
finally: | |
lock.release() | |
return decorator | |
class Proxy(object): | |
def __init__(self, obj): | |
self.obj = obj | |
def __getattr__(self, attr): | |
if isinstance(getattr(self.obj, attr), types.MethodType): | |
return method_lock(getattr(self.obj, attr)) | |
else: | |
return getattr(self.obj, attr) | |
def __setattr__(self, attr, value): | |
return super(Proxy, self).__setattr__(attr, value) | |
class Foo(object): | |
def bar(self, *args, **kwargs): | |
raise StandardError() | |
if __name__ == '__main__': | |
foo = Proxy(Foo()) | |
foo.bar() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment