forked from joshuag/speakerbot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic_class.py
More file actions
89 lines (58 loc) · 2.48 KB
/
dynamic_class.py
File metadata and controls
89 lines (58 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
This falls into my "bad idea that I'm playing with" category. Withold judgement and ye lunches.
Upgraded to plausible.
"""
from importlib import import_module
class Singleton(type):
instance_list = {}
def __call__(klass, *args, **kwargs):
if not klass in klass.instance_list:
klass.instance_list[klass] = super(Singleton, klass).__call__(*args, **kwargs)
return klass.instance_list[klass]
class MissingPluginException(Exception):
pass
class attach_methods(object):
def __init__(self, *modules, **kwargs):
self.methods = {}
#allow installing the functions under a specific dictionary
self.method_dict_name = kwargs.get("method_dict_name", None)
self.filter_attribute = kwargs.get("filter_attribute", None)
self.modules = modules
self.methods = {}
def __call__(self, klass):
self.get_methods(klass)
self.install_methods(klass)
return klass
def get_methods(self, klass):
filter_attribute = getattr(klass, "filter_attribute", self.filter_attribute)
for _module in self.modules:
imported_module = import_module(_module)
for method in dir(imported_module):
resolved_method = getattr(imported_module, method)
if (method[0:2] != "__" and not filter_attribute) or (filter_attribute and getattr(resolved_method, filter_attribute, False)):
self.methods[method] = resolved_method
def install_methods(self, klass):
method_dict_name = getattr(klass, "method_dict_name", self.method_dict_name)
if method_dict_name:
setattr(klass, method_dict_name, self.methods)
else:
for method in self.methods:
setattr(klass, method, self.methods[method])
def plugin(func):
def wrapped(*args, **kwargs):
print "Executing " + func.__name__
return func(*args, **kwargs)
set_function_attribute(wrapped, "plugin", True)
return wrapped
def set_function_attribute(func, name, value):
setattr(func, name, value)
class PluggableObject(object):
filter_attribute = "plugin"
method_dict_name = "plugins"
def __init__(self):
pass
def dispatch_plugin(self, name, *args, **kwargs):
try:
return self.plugins[name](self, *args, **kwargs)
except KeyError:
raise MissingPluginException("There is not a plugin installed for %s" % name)