Attachment 'objproxy.py'
Download 1 """ Object proxy
2
3 Getting into the middle between some application code and e.g.
4 some library module by intercepting all calls and logging all results.
5 """
6 from types import *
7
8 class Proxy(object):
9 def __init__(self, wrapped):
10 # remember the object we wrap:
11 self.wrapped = wrapped
12 # for prettier logging - find out name of object:
13 if hasattr(wrapped, '__name__'):
14 self.name = wrapped.__name__
15 elif hasattr(wrapped, '__class__'):
16 self.name = wrapped.__class__
17 else:
18 self.name = 'Unknown'
19
20 def log(self, format, *args):
21 print "Proxy: %s." % self.name + format % args
22
23 def need_proxy(self, obj):
24 """ checks if we need a proxy object """
25 # XXX is there a better way to check if we want to proxy?
26 if isinstance(obj, (
27 NoneType,
28 TypeType,
29 IntType,
30 LongType,
31 FloatType,
32 BooleanType,
33 ComplexType,
34 StringTypes,
35 BufferType,
36 TupleType,
37 ListType,
38 DictType,
39 DictProxyType,
40 GeneratorType,
41 BuiltinFunctionType,
42 BuiltinMethodType,
43 ClassType,
44 UnboundMethodType,
45 FileType,
46 XRangeType,
47 SliceType,
48 EllipsisType,
49 NotImplementedType,
50 )):
51 # it is something simple, we don't need a proxy
52 return False
53
54 if isinstance(obj, (
55 FunctionType,
56 InstanceType,
57 MethodType,
58 ModuleType,
59 )):
60 # something complex, like functions, class instances, modules, ...
61 return True
62
63 # something not listed above
64 return False
65
66 def __getattr__(self, name):
67 wrapped = getattr(self.wrapped, name)
68 if self.need_proxy(wrapped):
69 return Proxy(wrapped)
70 else:
71 self.log("%s -> %r", name, wrapped)
72 return wrapped
73
74 def __call__(self, *args, **kw):
75 result = self.wrapped(*args, **kw)
76 self.log("call(%r %r) --> %r", args, kw, result)
77 if self.need_proxy(result):
78 return Proxy(result)
79 else:
80 return result
81
82 # testing (all output generated comes from the proxy):
83 if __name__ == '__main__':
84 import sys
85 import ldap
86 ldap = sys.modules['ldap'] = Proxy(sys.modules['ldap'])
87
88 ldap.PORT
89 lo = ldap.initialize("ldap://localhost")
90 lo.timelimit
Attached Files
To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.You are not allowed to attach a file to this page.