Apparently the code to forestall Tk eating events was too aggressive (Tk user input...
[python/dscho.git] / Lib / test / test_coercion.py
blobd39e6fd046e1a675cbb232c235898cdaddadd4b2
1 import copy
2 import sys
4 # Fake a number that implements numeric methods through __coerce__
5 class CoerceNumber:
6 def __init__(self, arg):
7 self.arg = arg
9 def __repr__(self):
10 return '<CoerceNumber %s>' % repr(self.arg)
12 def __coerce__(self, other):
13 if isinstance(other, CoerceNumber):
14 return self.arg, other.arg
15 else:
16 return (self.arg, other)
19 # Fake a number that implements numeric ops through methods.
20 class MethodNumber:
22 def __init__(self,arg):
23 self.arg = arg
25 def __repr__(self):
26 return '<MethodNumber %s>' % repr(self.arg)
28 def __add__(self,other):
29 return self.arg + other
31 def __radd__(self,other):
32 return other + self.arg
34 def __sub__(self,other):
35 return self.arg - other
37 def __rsub__(self,other):
38 return other - self.arg
40 def __mul__(self,other):
41 return self.arg * other
43 def __rmul__(self,other):
44 return other * self.arg
46 def __div__(self,other):
47 return self.arg / other
49 def __rdiv__(self,other):
50 return other / self.arg
52 def __pow__(self,other):
53 return self.arg ** other
55 def __rpow__(self,other):
56 return other ** self.arg
58 def __mod__(self,other):
59 return self.arg % other
61 def __rmod__(self,other):
62 return other % self.arg
64 def __cmp__(self, other):
65 return cmp(self.arg, other)
68 candidates = [ 2, 4.0, 2L, 2+0j, [1], (2,), None,
69 MethodNumber(1), CoerceNumber(2)]
71 infix_binops = [ '+', '-', '*', '/', '**', '%' ]
72 prefix_binops = [ 'divmod' ]
74 def 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
99 def 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
112 do_infix_binops()
113 do_prefix_binops()