blob: d39e6fd046e1a675cbb232c235898cdaddadd4b2 [file] [log] [blame]
Neil Schemenauerfd288c72001-01-02 16:30:31 +00001import copy
2import sys
3
4# Fake a number that implements numeric methods through __coerce__
5class CoerceNumber:
6 def __init__(self, arg):
7 self.arg = arg
8
9 def __repr__(self):
10 return '<CoerceNumber %s>' % repr(self.arg)
11
12 def __coerce__(self, other):
13 if isinstance(other, CoerceNumber):
14 return self.arg, other.arg
15 else:
16 return (self.arg, other)
17
18
19# Fake a number that implements numeric ops through methods.
20class MethodNumber:
21
22 def __init__(self,arg):
23 self.arg = arg
24
25 def __repr__(self):
26 return '<MethodNumber %s>' % repr(self.arg)
27
28 def __add__(self,other):
29 return self.arg + other
30
31 def __radd__(self,other):
32 return other + self.arg
33
34 def __sub__(self,other):
35 return self.arg - other
36
37 def __rsub__(self,other):
38 return other - self.arg
39
40 def __mul__(self,other):
41 return self.arg * other
42
43 def __rmul__(self,other):
44 return other * self.arg
45
46 def __div__(self,other):
47 return self.arg / other
48
49 def __rdiv__(self,other):
50 return other / self.arg
51
52 def __pow__(self,other):
53 return self.arg ** other
54
55 def __rpow__(self,other):
56 return other ** self.arg
57
58 def __mod__(self,other):
59 return self.arg % other
60
61 def __rmod__(self,other):
62 return other % self.arg
63
64 def __cmp__(self, other):
65 return cmp(self.arg, other)
66
67
Neil Schemenauer38796d02001-01-03 01:52:11 +000068candidates = [ 2, 4.0, 2L, 2+0j, [1], (2,), None,
69 MethodNumber(1), CoerceNumber(2)]
Neil Schemenauerfd288c72001-01-02 16:30:31 +000070
71infix_binops = [ '+', '-', '*', '/', '**', '%' ]
72prefix_binops = [ 'divmod' ]
73
74def do_infix_binops():
75 for a in candidates:
76 for b in candidates:
77 for op in infix_binops:
78 print '%s %s %s' % (a, op, b),
79 try:
80 x = eval('a %s b' % op)
81 except:
82 error = sys.exc_info()[:2]
83 print '... %s' % error[0]
84 else:
85 print '=', x
86 try:
87 z = copy.copy(a)
88 except copy.Error:
89 z = a # assume it has no inplace ops
90 print '%s %s= %s' % (a, op, b),
91 try:
92 exec('z %s= b' % op)
93 except:
94 error = sys.exc_info()[:2]
95 print '... %s' % error[0]
96 else:
97 print '=>', z
98
99def do_prefix_binops():
100 for a in candidates:
101 for b in candidates:
102 for op in prefix_binops:
103 print '%s(%s, %s)' % (op, a, b),
104 try:
105 x = eval('%s(a, b)' % op)
106 except:
107 error = sys.exc_info()[:2]
108 print '... %s' % error[0]
109 else:
110 print '=', x
111
112do_infix_binops()
113do_prefix_binops()