Debian Codegraph @

lib_pypy/tputil.py

raw symbols SCIP
1 """
2
3 application level support module for transparent proxies.
4
5 """
6 from __pypy__ import tproxy
7 from types import MethodType
8
9 _dummy = object()
10 origtype = type
11
12 def make_proxy(controller, type=_dummy, obj=_dummy):
13 """ return a tranparent proxy controlled by the given
14 'controller' callable. The proxy will appear
15 as a completely regular instance of the given
16 type but all operations on it are send to the
17 specified controller - which receives on
18 ProxyOperation instance on each such call.
19 A non-specified type will default to type(obj)
20 if obj is specified.
21 """
22 if type is _dummy:
23 if obj is _dummy:
24 raise TypeError("you must specify a type or an instance obj of it")
25 type = origtype(obj)
26 def perform(opname, *args, **kwargs):
27 operation = ProxyOperation(tp, obj, opname, args, kwargs)
28 return controller(operation)
29 tp = tproxy(type, perform)
30 return tp
31
32 class ProxyOperation(object):
33 def __init__(self, proxyobj, obj, opname, args, kwargs):
34 self.proxyobj = proxyobj
35 self.opname = opname
36 self.args = args
37 self.kwargs = kwargs
38 if obj is not _dummy:
39 self.obj = obj
40
41 def delegate(self):
42 """ return result from delegating this operation to the
43 underyling self.obj - which must exist and is usually
44 provided through the initial make_proxy(..., obj=...)
45 creation.
46 """
47 try:
48 obj = getattr(self, 'obj')
49 except AttributeError:
50 raise TypeError("proxy does not have an underlying 'obj', "
51 "cannot delegate")
52 objattr = getattr(obj, self.opname)
53 res = objattr(*self.args, **self.kwargs)
54 if self.opname == "__getattribute__":
55 if (isinstance(res, MethodType) and
56 res.__self__ is self.instance):
57 res = MethodType(res.__func__, self.proxyobj, res.__self__.__class__)
58 if res is self.obj:
59 res = self.proxyobj
60 return res
61
62 def __repr__(self):
63 args = ", ".join([repr(x) for x in self.args])
64 args = "<0x%x>, " % id(self.proxyobj) + args
65 if self.kwargs:
66 args += ", ".join(["%s=%r" % item
67 for item in self.kwargs.items()])
68 return "<ProxyOperation %s.%s(%s)>" %(
69 type(self.proxyobj).__name__, self.opname, args)