4 # Fake a number that implements numeric methods through __coerce__
6 def __init__(self
, arg
):
10 return '<CoerceNumber %s>' % repr(self
.arg
)
12 def __coerce__(self
, other
):
13 if isinstance(other
, CoerceNumber
):
14 return self
.arg
, other
.arg
16 return (self
.arg
, other
)
19 # Fake a number that implements numeric ops through methods.
22 def __init__(self
,arg
):
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():
77 for op
in infix_binops
:
78 print '%s %s %s' % (a
, op
, b
),
80 x
= eval('a %s b' % op
)
82 error
= sys
.exc_info()[:2]
83 print '... %s' % error
[0]
89 z
= a
# assume it has no inplace ops
90 print '%s %s= %s' % (a
, op
, b
),
94 error
= sys
.exc_info()[:2]
95 print '... %s' % error
[0]
99 def do_prefix_binops():
102 for op
in prefix_binops
:
103 print '%s(%s, %s)' % (op
, a
, b
),
105 x
= eval('%s(a, b)' % op
)
107 error
= sys
.exc_info()[:2]
108 print '... %s' % error
[0]