MCPcopy Create free account
hub / github.com/ActiveState/code / Proxy

Class Proxy

recipes/Python/496741_Object_Proxying/recipe-496741.py:1–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Proxy(object):
2 __slots__ = ["_obj", "__weakref__"]
3 def __init__(self, obj):
4 object.__setattr__(self, "_obj", obj)
5
6 #
7 # proxying (special cases)
8 #
9 def __getattribute__(self, name):
10 return getattr(object.__getattribute__(self, "_obj"), name)
11 def __delattr__(self, name):
12 delattr(object.__getattribute__(self, "_obj"), name)
13 def __setattr__(self, name, value):
14 setattr(object.__getattribute__(self, "_obj"), name, value)
15
16 def __nonzero__(self):
17 return bool(object.__getattribute__(self, "_obj"))
18 def __str__(self):
19 return str(object.__getattribute__(self, "_obj"))
20 def __repr__(self):
21 return repr(object.__getattribute__(self, "_obj"))
22
23 #
24 # factories
25 #
26 _special_names = [
27 '__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',
28 '__contains__', '__delitem__', '__delslice__', '__div__', '__divmod__',
29 '__eq__', '__float__', '__floordiv__', '__ge__', '__getitem__',
30 '__getslice__', '__gt__', '__hash__', '__hex__', '__iadd__', '__iand__',
31 '__idiv__', '__idivmod__', '__ifloordiv__', '__ilshift__', '__imod__',
32 '__imul__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__',
33 '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__',
34 '__long__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__',
35 '__neg__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__',
36 '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__',
37 '__repr__', '__reversed__', '__rfloorfiv__', '__rlshift__', '__rmod__',
38 '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
39 '__rtruediv__', '__rxor__', '__setitem__', '__setslice__', '__sub__',
40 '__truediv__', '__xor__', 'next',
41 ]
42
43 @classmethod
44 def _create_class_proxy(cls, theclass):
45 """creates a proxy for the given class"""
46
47 def make_method(name):
48 def method(self, *args, **kw):
49 return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw)
50 return method
51
52 namespace = {}
53 for name in cls._special_names:
54 if hasattr(theclass, name):
55 namespace[name] = make_method(name)
56 return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace)
57
58 def __new__(cls, obj, *args, **kwargs):
59 """
60 creates an proxy instance referencing `obj`. (obj, *args, **kwargs) are

Callers 3

recipe-496741.pyFile · 0.70
__new__Method · 0.50
__new__Method · 0.50

Calls

no outgoing calls

Tested by

no test coverage detected