Skip to content

Instantly share code, notes, and snippets.

@enkore
Created May 20, 2012 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enkore/2757637 to your computer and use it in GitHub Desktop.
Save enkore/2757637 to your computer and use it in GitHub Desktop.
DynamicProxy
class DynamicProxy(object):
class Task(object):
fn = None
args = list()
kwargs = dict()
def __init__(self, target, target_proxy=None):
self._target = target
self._methods = inspect.getmembers(target, inspect.ismethod)
print "Methods: %s" % self._methods
self._queue = Queue.Queue()
if not target_proxy:
target.__queue = self._queue
for name, bound_method in self._methods:
#argspec = ",".join(["object" for o in inspect.getargspec(bound_method)[0]])
#argnames = list()
#i = 0
#for o in inspect.getargspec(bound_method)[0]:
# argnames.append("arg%s" % i)
# i += 1
#argnames = ",".join([o for o in argnames])
proxy_generator = """def %s(self, *args, **kwargs):
task = DynamicProxy.Task()
task.fn = self.%s._target
task.args = args
task.kwargs = kwargs
self._queue.put(task)""" % (name, name)
proxy = locals()
proxy["target"] = bound_method
exec proxy_generator in globals(), proxy
proxy[name]._target = bound_method
setattr(self, name, types.MethodType(proxy[name], self, self.__class__))
for attribute in ["__module__", "__name__", "__doc__"]:
try:
setattr(getattr(self, name), attribute, getattr(bound_method, attribute))
except:
pass
def adv_getattr(self, attr):
print self, attr
if hasattr(self, attr):
return getattr(self, attr)
elif hasattr(self.__proxy, attr):
return getattr(self.__proxy, attr)
else:
raise AttributeError()
target.__getattr__ = types.MethodType(adv_getattr, target, target.__class__)
print target.__getattr__
target.__getattr__("__queue")
print "self. %s" % dir(self)
if not target_proxy:
print "Creating own thread..."
self._thread = threading.Thread(target=self._run)
self._thread.daemon = True
self._thread.start()
else:
print "Using existing queue"
self._queue = target_proxy.__queue
print "FINISHED"
def run(self):
pass
def _run(self):
while self.run:
task = self._queue.get()
try:
task.fn(*task.args, **task.kwargs)
except:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment