Skip to content

Instantly share code, notes, and snippets.

@HelloZeroNet
Created March 21, 2015 17:26
Show Gist options
  • Save HelloZeroNet/f2d51a35624ee1c84a4d to your computer and use it in GitHub Desktop.
Save HelloZeroNet/f2d51a35624ee1c84a4d to your computer and use it in GitHub Desktop.
plugined_cache = {}
plugins = {}
def plugined(base_class):
class_name = base_class.__name__
if class_name in plugined_cache:
PluginedClass = plugined_cache[class_name]
else:
classes = plugins[class_name]+[base_class]
classes.reverse()
PluginedClass = type(class_name, tuple(classes), dict())
plugined_cache[class_name] = PluginedClass
return PluginedClass
def accept(base_class):
class_name = base_class.__name__
classes = plugins[class_name]
classes.reverse()
classes.append(base_class)
PluginedClass = type(class_name, tuple(classes), dict())
return PluginedClass
def to(class_name):
if class_name not in plugins: plugins[class_name] = []
def classDecorator(self):
plugins[class_name].append(self)
return self
return classDecorator
@to("Request")
class RequestPlugin(object):
def route1(self, req):
return self.name, "Hello Plugin"
@to("Request")
class RequestPlugin2(object):
def route2(self, req):
return self.name, "Hello Plugin2"
@to("Request")
class RequestOverride(object):
def route(self, req):
back = super(RequestOverride, self).route(req)
return self.name, "Overrided:", back
@accept
class Request(object):
def __init__(self, name):
self.name = name
def route(self, req):
return self.name, "Hello base"
import time
s = time.time()
for i in range(100000):
request = Request("requester")
back = request.route2("hello")
print "With 3 plugin", time.time()-s, back
class Request(object):
def __init__(self, name):
self.name = name
def route(self, req):
return self.name, "Hello base"
import time
s = time.time()
for i in range(100000):
request = Request("requester")
back = request.route("hello")
print "Without plugin", time.time()-s, back
"""
With 3 plugin 0.201000213623 ('requester', 'Hello Plugin2')
Without plugin 0.198999881744 ('requester', 'Hello base')
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment