Skip to content

Instantly share code, notes, and snippets.

@beanyoung
Created October 14, 2013 02:29
Show Gist options
  • Save beanyoung/6969790 to your computer and use it in GitHub Desktop.
Save beanyoung/6969790 to your computer and use it in GitHub Desktop.
A proxy that ensures only one method of class is running.
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