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
24 ## Decimal has all of the methods specified by the Real abc, but it should
25 ## not be registered as a Real because decimals do not interoperate with
26 ## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But,
27 ## abstract reals are expected to interoperate (i.e. R1 + R2 should be
28 ## expected to work if R1 and R2 are both Reals).
30 class Complex(Number
):
31 """Complex defines the operations that work on the builtin complex type.
33 In short, those are: a conversion to complex, .real, .imag, +, -,
34 *, /, abs(), .conjugate, ==, and !=.
36 If it is given heterogenous arguments, and doesn't have special
37 knowledge about them, it should fall back to the builtin complex
38 type as described below.
42 def __complex__(self
):
43 """Return a builtin complex instance. Called for complex(self)."""
45 # Will be __bool__ in 3.0.
46 def __nonzero__(self
):
47 """True if self != 0. Called for bool(self)."""
52 """Retrieve the real component of this number.
54 This should subclass Real.
56 raise NotImplementedError
60 """Retrieve the real component of this number.
62 This should subclass Real.
64 raise NotImplementedError
67 def __add__(self
, other
):
69 raise NotImplementedError
72 def __radd__(self
, other
):
74 raise NotImplementedError
79 raise NotImplementedError
84 raise NotImplementedError
86 def __sub__(self
, other
):
90 def __rsub__(self
, other
):
95 def __mul__(self
, other
):
97 raise NotImplementedError
100 def __rmul__(self
, other
):
102 raise NotImplementedError
105 def __div__(self
, other
):
106 """self / other without __future__ division
108 May promote to float.
110 raise NotImplementedError
113 def __rdiv__(self
, other
):
114 """other / self without __future__ division"""
115 raise NotImplementedError
118 def __truediv__(self
, other
):
119 """self / other with __future__ division.
121 Should promote to float when necessary.
123 raise NotImplementedError
126 def __rtruediv__(self
, other
):
127 """other / self with __future__ division"""
128 raise NotImplementedError
131 def __pow__(self
, exponent
):
132 """self**exponent; should promote to float or complex when necessary."""
133 raise NotImplementedError
136 def __rpow__(self
, base
):
138 raise NotImplementedError
142 """Returns the Real distance from 0. Called for abs(self)."""
143 raise NotImplementedError
147 """(x+y*i).conjugate() returns (x-y*i)."""
148 raise NotImplementedError
151 def __eq__(self
, other
):
153 raise NotImplementedError
155 def __ne__(self
, other
):
157 # The default __ne__ doesn't negate __eq__ until 3.0.
158 return not (self
== other
)
160 Complex
.register(complex)
164 """To Complex, Real adds the operations that work on real numbers.
166 In short, those are: a conversion to float, trunc(), divmod,
169 Real also provides defaults for the derived operations.
174 """Any Real can be converted to a native float object.
176 Called for float(self)."""
177 raise NotImplementedError
181 """trunc(self): Truncates self to an Integral.
183 Returns an Integral i such that:
185 * abs(i) <= abs(self);
186 * for any Integral j satisfying the first two conditions,
187 abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
188 i.e. "truncate towards 0".
190 raise NotImplementedError
192 def __divmod__(self
, other
):
193 """divmod(self, other): The pair (self // other, self % other).
195 Sometimes this can be computed faster than the pair of
198 return (self
// other
, self
% other
)
200 def __rdivmod__(self
, other
):
201 """divmod(other, self): The pair (self // other, self % other).
203 Sometimes this can be computed faster than the pair of
206 return (other
// self
, other
% self
)
209 def __floordiv__(self
, other
):
210 """self // other: The floor() of self/other."""
211 raise NotImplementedError
214 def __rfloordiv__(self
, other
):
215 """other // self: The floor() of other/self."""
216 raise NotImplementedError
219 def __mod__(self
, other
):
221 raise NotImplementedError
224 def __rmod__(self
, other
):
226 raise NotImplementedError
229 def __lt__(self
, other
):
232 < on Reals defines a total ordering, except perhaps for NaN."""
233 raise NotImplementedError
236 def __le__(self
, other
):
238 raise NotImplementedError
240 # Concrete implementations of Complex abstract methods.
241 def __complex__(self
):
242 """complex(self) == complex(float(self), 0)"""
243 return complex(float(self
))
247 """Real numbers are their real component."""
252 """Real numbers have no imaginary component."""
256 """Conjugate is a no-op for Reals."""
262 class Rational(Real
):
263 """.numerator and .denominator should be in lowest terms."""
267 raise NotImplementedError
270 def denominator(self
):
271 raise NotImplementedError
273 # Concrete implementation of Real's conversion to float.
275 """float(self) = self.numerator / self.denominator
277 It's important that this conversion use the integer's "true"
278 division rather than casting one side to float before dividing
279 so that ratios of huge integers convert without overflowing.
282 return self
.numerator
/ self
.denominator
285 class Integral(Rational
):
286 """Integral adds a conversion to long and the bit-string operations."""
291 raise NotImplementedError
298 def __pow__(self
, exponent
, modulus
=None):
299 """self ** exponent % modulus, but maybe faster.
301 Accept the modulus argument if you want to support the
302 3-argument version of pow(). Raise a TypeError if exponent < 0
303 or any argument isn't Integral. Otherwise, just implement the
304 2-argument version described in Complex.
306 raise NotImplementedError
309 def __lshift__(self
, other
):
311 raise NotImplementedError
314 def __rlshift__(self
, other
):
316 raise NotImplementedError
319 def __rshift__(self
, other
):
321 raise NotImplementedError
324 def __rrshift__(self
, other
):
326 raise NotImplementedError
329 def __and__(self
, other
):
331 raise NotImplementedError
334 def __rand__(self
, other
):
336 raise NotImplementedError
339 def __xor__(self
, other
):
341 raise NotImplementedError
344 def __rxor__(self
, other
):
346 raise NotImplementedError
349 def __or__(self
, other
):
351 raise NotImplementedError
354 def __ror__(self
, other
):
356 raise NotImplementedError
359 def __invert__(self
):
361 raise NotImplementedError
363 # Concrete implementations of Rational and Real abstract methods.
365 """float(self) == float(long(self))"""
366 return float(long(self
))
370 """Integers are their own numerators."""
374 def denominator(self
):
375 """Integers have a denominator of 1."""
378 Integral
.register(int)
379 Integral
.register(long)