Debian Codegraph @

rpython/tool/pairtype.py

raw symbols SCIP
1 """
2 Two magic tricks for classes:
3
4 class X:
5 __metaclass__ = extendabletype
6 ...
7
8 # in some other file...
9 class __extend__(X):
10 ... # and here you can add new methods and class attributes to X
11
12 Mostly useful together with the second trick, which lets you build
13 methods whose 'self' is a pair of objects instead of just one:
14
15 class __extend__(pairtype(X, Y)):
16 attribute = 42
17 def method((x, y), other, arguments):
18 ...
19
20 pair(x, y).attribute
21 pair(x, y).method(other, arguments)
22
23 This finds methods and class attributes based on the actual
24 class of both objects that go into the pair(), with the usual
25 rules of method/attribute overriding in (pairs of) subclasses.
26
27 For more information, see test_pairtype.
28 """
29
30 class extendabletype(type):
31 """A type with a syntax trick: 'class __extend__(t)' actually extends
32 the definition of 't' instead of creating a new subclass."""
33 def __new__(cls, name, bases, dict):
34 if name == '__extend__':
35 for cls in bases:
36 for key, value in dict.items():
37 if key == '__module__':
38 continue
39 # XXX do we need to provide something more for pickling?
40 setattr(cls, key, value)
41 return None
42 else:
43 return super(extendabletype, cls).__new__(cls, name, bases, dict)
44
45
46 def pair(a, b):
47 """Return a pair object."""
48 tp = pairtype(a.__class__, b.__class__)
49 return tp((a, b)) # tp is a subclass of tuple
50
51 pairtypecache = {}
52
53 def pairtype(cls1, cls2):
54 """type(pair(a,b)) is pairtype(a.__class__, b.__class__)."""
55 try:
56 pair = pairtypecache[cls1, cls2]
57 except KeyError:
58 name = 'pairtype(%s, %s)' % (cls1.__name__, cls2.__name__)
59 bases1 = [pairtype(base1, cls2) for base1 in cls1.__bases__]
60 bases2 = [pairtype(cls1, base2) for base2 in cls2.__bases__]
61 bases = tuple(bases1 + bases2) or (tuple,) # 'tuple': ultimate base
62 pair = pairtypecache[cls1, cls2] = extendabletype(name, bases, {})
63 return pair
64
65 def pairmro(cls1, cls2):
66 """
67 Return the resolution order on pairs of types for double dispatch.
68
69 This order is compatible with the mro of pairtype(cls1, cls2).
70 """
71 for base2 in cls2.__mro__:
72 for base1 in cls1.__mro__:
73 yield (base1, base2)
74
75 class DoubleDispatchRegistry(object):
76 """
77 A mapping of pairs of types to arbitrary objects respecting inheritance
78 """
79 def __init__(self):
80 self._registry = {}
81 self._cache = {}
82
83 def __getitem__(self, clspair):
84 try:
85 return self._cache[clspair]
86 except KeyError:
87 cls1, cls2 = clspair
88 for c1, c2 in pairmro(cls1, cls2):
89 if (c1, c2) in self._cache:
90 return self._cache[(c1, c2)]
91 else:
92 raise
93
94 def __setitem__(self, clspair, value):
95 self._registry[clspair] = value
96 self._cache = self._registry.copy()
97
98 def doubledispatch(func):
99 """
100 Decorator returning a double-dispatch function
101
102 Usage
103 -----
104 >>> @doubledispatch
105 ... def func(x, y):
106 ... return 0
107 >>> @func.register(basestring, basestring)
108 ... def func_string_string(x, y):
109 ... return 42
110 >>> func(1, 2)
111 0
112 >>> func('x', u'y')
113 42
114 """
115 return DoubleDispatchFunction(func)
116
117 class DoubleDispatchFunction(object):
118 def __init__(self, func):
119 self._registry = DoubleDispatchRegistry()
120 self._default = func
121
122 def __call__(self, arg1, arg2, *args, **kwargs):
123 try:
124 func = self._registry[type(arg1), type(arg2)]
125 except KeyError:
126 func = self._default
127 return func(arg1, arg2, *args, **kwargs)
128
129 def register(self, cls1, cls2):
130 def decorator(func):
131 self._registry[cls1, cls2] = func
132 return func
133 return decorator