1 # Copyright 2007 Google, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Abstract Base Classes (ABCs) for numbers, according to PEP 3141.
6 TODO: Fill out more detailed documentation on the operators."""
8 from __future__
import division
9 from abc
import ABCMeta
, abstractmethod
, abstractproperty
11 __all__
= ["Number", "Complex", "Real", "Rational", "Integral"]
14 """All numbers inherit from this class.
16 If you just want to check if an argument x is a number, without
17 caring what kind, use isinstance(x, Number).
19 __metaclass__
= ABCMeta
22 # Concrete numeric types must provide their own hash implementation
28 ## Decimal has all of the methods specified by the Real abc, but it should
29 ## not be registered as a Real because decimals do not interoperate with
30 ## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But,
31 ## abstract reals are expected to interoperate (i.e. R1 + R2 should be
32 ## expected to work if R1 and R2 are both Reals).
34 class Complex(Number
):
35 """Complex defines the operations that work on the builtin complex type.
37 In short, those are: a conversion to complex, .real, .imag, +, -,
38 *, /, abs(), .conjugate, ==, and !=.
40 If it is given heterogenous arguments, and doesn't have special
41 knowledge about them, it should fall back to the builtin complex
42 type as described below.
48 def __complex__(self
):
49 """Return a builtin complex instance. Called for complex(self)."""
51 # Will be __bool__ in 3.0.
52 def __nonzero__(self
):
53 """True if self != 0. Called for bool(self)."""
58 """Retrieve the real component of this number.
60 This should subclass Real.
62 raise NotImplementedError
66 """Retrieve the real component of this number.
68 This should subclass Real.
70 raise NotImplementedError
73 def __add__(self
, other
):
75 raise NotImplementedError
78 def __radd__(self
, other
):
80 raise NotImplementedError
85 raise NotImplementedError
90 raise NotImplementedError
92 def __sub__(self
, other
):
96 def __rsub__(self
, other
):
101 def __mul__(self
, other
):
103 raise NotImplementedError
106 def __rmul__(self
, other
):
108 raise NotImplementedError
111 def __div__(self
, other
):
112 """self / other without __future__ division
114 May promote to float.
116 raise NotImplementedError
119 def __rdiv__(self
, other
):
120 """other / self without __future__ division"""
121 raise NotImplementedError
124 def __truediv__(self
, other
):
125 """self / other with __future__ division.
127 Should promote to float when necessary.
129 raise NotImplementedError
132 def __rtruediv__(self
, other
):
133 """other / self with __future__ division"""
134 raise NotImplementedError
137 def __pow__(self
, exponent
):
138 """self**exponent; should promote to float or complex when necessary."""
139 raise NotImplementedError
142 def __rpow__(self
, base
):
144 raise NotImplementedError
148 """Returns the Real distance from 0. Called for abs(self)."""
149 raise NotImplementedError
153 """(x+y*i).conjugate() returns (x-y*i)."""
154 raise NotImplementedError
157 def __eq__(self
, other
):
159 raise NotImplementedError
161 def __ne__(self
, other
):
163 # The default __ne__ doesn't negate __eq__ until 3.0.
164 return not (self
== other
)
166 Complex
.register(complex)
170 """To Complex, Real adds the operations that work on real numbers.
172 In short, those are: a conversion to float, trunc(), divmod,
175 Real also provides defaults for the derived operations.
182 """Any Real can be converted to a native float object.
184 Called for float(self)."""
185 raise NotImplementedError
189 """trunc(self): Truncates self to an Integral.
191 Returns an Integral i such that:
193 * abs(i) <= abs(self);
194 * for any Integral j satisfying the first two conditions,
195 abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
196 i.e. "truncate towards 0".
198 raise NotImplementedError
200 def __divmod__(self
, other
):
201 """divmod(self, other): The pair (self // other, self % other).
203 Sometimes this can be computed faster than the pair of
206 return (self
// other
, self
% other
)
208 def __rdivmod__(self
, other
):
209 """divmod(other, self): The pair (self // other, self % other).
211 Sometimes this can be computed faster than the pair of
214 return (other
// self
, other
% self
)
217 def __floordiv__(self
, other
):
218 """self // other: The floor() of self/other."""
219 raise NotImplementedError
222 def __rfloordiv__(self
, other
):
223 """other // self: The floor() of other/self."""
224 raise NotImplementedError
227 def __mod__(self
, other
):
229 raise NotImplementedError
232 def __rmod__(self
, other
):
234 raise NotImplementedError
237 def __lt__(self
, other
):
240 < on Reals defines a total ordering, except perhaps for NaN."""
241 raise NotImplementedError
244 def __le__(self
, other
):
246 raise NotImplementedError
248 # Concrete implementations of Complex abstract methods.
249 def __complex__(self
):
250 """complex(self) == complex(float(self), 0)"""
251 return complex(float(self
))
255 """Real numbers are their real component."""
260 """Real numbers have no imaginary component."""
264 """Conjugate is a no-op for Reals."""
270 class Rational(Real
):
271 """.numerator and .denominator should be in lowest terms."""
277 raise NotImplementedError
280 def denominator(self
):
281 raise NotImplementedError
283 # Concrete implementation of Real's conversion to float.
285 """float(self) = self.numerator / self.denominator
287 It's important that this conversion use the integer's "true"
288 division rather than casting one side to float before dividing
289 so that ratios of huge integers convert without overflowing.
292 return self
.numerator
/ self
.denominator
295 class Integral(Rational
):
296 """Integral adds a conversion to long and the bit-string operations."""
303 raise NotImplementedError
310 def __pow__(self
, exponent
, modulus
=None):
311 """self ** exponent % modulus, but maybe faster.
313 Accept the modulus argument if you want to support the
314 3-argument version of pow(). Raise a TypeError if exponent < 0
315 or any argument isn't Integral. Otherwise, just implement the
316 2-argument version described in Complex.
318 raise NotImplementedError
321 def __lshift__(self
, other
):
323 raise NotImplementedError
326 def __rlshift__(self
, other
):
328 raise NotImplementedError
331 def __rshift__(self
, other
):
333 raise NotImplementedError
336 def __rrshift__(self
, other
):
338 raise NotImplementedError
341 def __and__(self
, other
):
343 raise NotImplementedError
346 def __rand__(self
, other
):
348 raise NotImplementedError
351 def __xor__(self
, other
):
353 raise NotImplementedError
356 def __rxor__(self
, other
):
358 raise NotImplementedError
361 def __or__(self
, other
):
363 raise NotImplementedError
366 def __ror__(self
, other
):
368 raise NotImplementedError
371 def __invert__(self
):
373 raise NotImplementedError
375 # Concrete implementations of Rational and Real abstract methods.
377 """float(self) == float(long(self))"""
378 return float(long(self
))
382 """Integers are their own numerators."""
386 def denominator(self
):
387 """Integers have a denominator of 1."""
390 Integral
.register(int)
391 Integral
.register(long)