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