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
21 # Concrete numeric types must provide their own hash implementation
27 ## Decimal has all of the methods specified by the Real abc, but it should
28 ## not be registered as a Real because decimals do not interoperate with
29 ## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But,
30 ## abstract reals are expected to interoperate (i.e. R1 + R2 should be
31 ## expected to work if R1 and R2 are both Reals).
33 class Complex(Number
):
34 """Complex defines the operations that work on the builtin complex type.
36 In short, those are: a conversion to complex, .real, .imag, +, -,
37 *, /, abs(), .conjugate, ==, and !=.
39 If it is given heterogenous arguments, and doesn't have special
40 knowledge about them, it should fall back to the builtin complex
41 type as described below.
45 def __complex__(self
):
46 """Return a builtin complex instance. Called for complex(self)."""
48 # Will be __bool__ in 3.0.
49 def __nonzero__(self
):
50 """True if self != 0. Called for bool(self)."""
55 """Retrieve the real component of this number.
57 This should subclass Real.
59 raise NotImplementedError
63 """Retrieve the real component of this number.
65 This should subclass Real.
67 raise NotImplementedError
70 def __add__(self
, other
):
72 raise NotImplementedError
75 def __radd__(self
, other
):
77 raise NotImplementedError
82 raise NotImplementedError
87 raise NotImplementedError
89 def __sub__(self
, other
):
93 def __rsub__(self
, other
):
98 def __mul__(self
, other
):
100 raise NotImplementedError
103 def __rmul__(self
, other
):
105 raise NotImplementedError
108 def __div__(self
, other
):
109 """self / other without __future__ division
111 May promote to float.
113 raise NotImplementedError
116 def __rdiv__(self
, other
):
117 """other / self without __future__ division"""
118 raise NotImplementedError
121 def __truediv__(self
, other
):
122 """self / other with __future__ division.
124 Should promote to float when necessary.
126 raise NotImplementedError
129 def __rtruediv__(self
, other
):
130 """other / self with __future__ division"""
131 raise NotImplementedError
134 def __pow__(self
, exponent
):
135 """self**exponent; should promote to float or complex when necessary."""
136 raise NotImplementedError
139 def __rpow__(self
, base
):
141 raise NotImplementedError
145 """Returns the Real distance from 0. Called for abs(self)."""
146 raise NotImplementedError
150 """(x+y*i).conjugate() returns (x-y*i)."""
151 raise NotImplementedError
154 def __eq__(self
, other
):
156 raise NotImplementedError
158 def __ne__(self
, other
):
160 # The default __ne__ doesn't negate __eq__ until 3.0.
161 return not (self
== other
)
163 Complex
.register(complex)
167 """To Complex, Real adds the operations that work on real numbers.
169 In short, those are: a conversion to float, trunc(), divmod,
172 Real also provides defaults for the derived operations.
177 """Any Real can be converted to a native float object.
179 Called for float(self)."""
180 raise NotImplementedError
184 """trunc(self): Truncates self to an Integral.
186 Returns an Integral i such that:
188 * abs(i) <= abs(self);
189 * for any Integral j satisfying the first two conditions,
190 abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
191 i.e. "truncate towards 0".
193 raise NotImplementedError
195 def __divmod__(self
, other
):
196 """divmod(self, other): The pair (self // other, self % other).
198 Sometimes this can be computed faster than the pair of
201 return (self
// other
, self
% other
)
203 def __rdivmod__(self
, other
):
204 """divmod(other, self): The pair (self // other, self % other).
206 Sometimes this can be computed faster than the pair of
209 return (other
// self
, other
% self
)
212 def __floordiv__(self
, other
):
213 """self // other: The floor() of self/other."""
214 raise NotImplementedError
217 def __rfloordiv__(self
, other
):
218 """other // self: The floor() of other/self."""
219 raise NotImplementedError
222 def __mod__(self
, other
):
224 raise NotImplementedError
227 def __rmod__(self
, other
):
229 raise NotImplementedError
232 def __lt__(self
, other
):
235 < on Reals defines a total ordering, except perhaps for NaN."""
236 raise NotImplementedError
239 def __le__(self
, other
):
241 raise NotImplementedError
243 # Concrete implementations of Complex abstract methods.
244 def __complex__(self
):
245 """complex(self) == complex(float(self), 0)"""
246 return complex(float(self
))
250 """Real numbers are their real component."""
255 """Real numbers have no imaginary component."""
259 """Conjugate is a no-op for Reals."""
265 class Rational(Real
):
266 """.numerator and .denominator should be in lowest terms."""
270 raise NotImplementedError
273 def denominator(self
):
274 raise NotImplementedError
276 # Concrete implementation of Real's conversion to float.
278 """float(self) = self.numerator / self.denominator
280 It's important that this conversion use the integer's "true"
281 division rather than casting one side to float before dividing
282 so that ratios of huge integers convert without overflowing.
285 return self
.numerator
/ self
.denominator
288 class Integral(Rational
):
289 """Integral adds a conversion to long and the bit-string operations."""
294 raise NotImplementedError
301 def __pow__(self
, exponent
, modulus
=None):
302 """self ** exponent % modulus, but maybe faster.
304 Accept the modulus argument if you want to support the
305 3-argument version of pow(). Raise a TypeError if exponent < 0
306 or any argument isn't Integral. Otherwise, just implement the
307 2-argument version described in Complex.
309 raise NotImplementedError
312 def __lshift__(self
, other
):
314 raise NotImplementedError
317 def __rlshift__(self
, other
):
319 raise NotImplementedError
322 def __rshift__(self
, other
):
324 raise NotImplementedError
327 def __rrshift__(self
, other
):
329 raise NotImplementedError
332 def __and__(self
, other
):
334 raise NotImplementedError
337 def __rand__(self
, other
):
339 raise NotImplementedError
342 def __xor__(self
, other
):
344 raise NotImplementedError
347 def __rxor__(self
, other
):
349 raise NotImplementedError
352 def __or__(self
, other
):
354 raise NotImplementedError
357 def __ror__(self
, other
):
359 raise NotImplementedError
362 def __invert__(self
):
364 raise NotImplementedError
366 # Concrete implementations of Rational and Real abstract methods.
368 """float(self) == float(long(self))"""
369 return float(long(self
))
373 """Integers are their own numerators."""
377 def denominator(self
):
378 """Integers have a denominator of 1."""
381 Integral
.register(int)
382 Integral
.register(long)