blob: 8ab07d0b93d9be02e37ea4d094bb21627a7c308f [file] [log] [blame]
Christian Heimes072c0f12008-01-03 23:01:04 +00001:mod:`numbers` --- Numeric abstract base classes
2================================================
3
4.. module:: numbers
5 :synopsis: Numeric abstract base classes (Complex, Real, Integral, etc.).
6
Christian Heimesfaf2f632008-01-06 16:59:19 +00007
Éric Araujofa088db2011-06-04 18:42:38 +02008The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric
9:term:`abstract base classes <abstract base class>` which progressively define
10more operations. None of the types defined in this module can be instantiated.
Christian Heimes072c0f12008-01-03 23:01:04 +000011
12
13.. class:: Number
14
15 The root of the numeric hierarchy. If you just want to check if an argument
16 *x* is a number, without caring what kind, use ``isinstance(x, Number)``.
17
18
Christian Heimes072c0f12008-01-03 23:01:04 +000019The numeric tower
20-----------------
21
22.. class:: Complex
23
24 Subclasses of this type describe complex numbers and include the operations
Georg Brandlc5605df2009-08-13 08:26:44 +000025 that work on the built-in :class:`complex` type. These are: conversions to
Christian Heimes072c0f12008-01-03 23:01:04 +000026 :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``,
27 ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
28 except ``-`` and ``!=`` are abstract.
29
Benjamin Petersone41251e2008-04-25 01:59:09 +000030 .. attribute:: real
Christian Heimes072c0f12008-01-03 23:01:04 +000031
Mark Dickinsonbc5f75c2010-05-05 21:55:11 +000032 Abstract. Retrieves the real component of this number.
Christian Heimes072c0f12008-01-03 23:01:04 +000033
Benjamin Petersone41251e2008-04-25 01:59:09 +000034 .. attribute:: imag
Christian Heimes072c0f12008-01-03 23:01:04 +000035
Mark Dickinsonbc5f75c2010-05-05 21:55:11 +000036 Abstract. Retrieves the imaginary component of this number.
Christian Heimes072c0f12008-01-03 23:01:04 +000037
Benjamin Petersone41251e2008-04-25 01:59:09 +000038 .. method:: conjugate()
Christian Heimes072c0f12008-01-03 23:01:04 +000039
Benjamin Petersone41251e2008-04-25 01:59:09 +000040 Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate()
41 == (1-3j)``.
Christian Heimes072c0f12008-01-03 23:01:04 +000042
43.. class:: Real
44
45 To :class:`Complex`, :class:`Real` adds the operations that work on real
46 numbers.
47
Benjamin Petersonab2b7162011-03-12 11:58:15 -060048 In short, those are: a conversion to :class:`float`, :func:`math.trunc`,
Christian Heimes072c0f12008-01-03 23:01:04 +000049 :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``,
50 ``%``, ``<``, ``<=``, ``>``, and ``>=``.
51
Georg Brandl1f01deb2009-01-03 22:47:39 +000052 Real also provides defaults for :func:`complex`, :attr:`~Complex.real`,
53 :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`.
Christian Heimes072c0f12008-01-03 23:01:04 +000054
55
56.. class:: Rational
57
Christian Heimesf75b2902008-03-16 17:29:44 +000058 Subtypes :class:`Real` and adds
Georg Brandl1f01deb2009-01-03 22:47:39 +000059 :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which
Christian Heimes072c0f12008-01-03 23:01:04 +000060 should be in lowest terms. With these, it provides a default for
61 :func:`float`.
62
Benjamin Petersone41251e2008-04-25 01:59:09 +000063 .. attribute:: numerator
Christian Heimes072c0f12008-01-03 23:01:04 +000064
Benjamin Petersone41251e2008-04-25 01:59:09 +000065 Abstract.
Christian Heimes072c0f12008-01-03 23:01:04 +000066
Benjamin Petersone41251e2008-04-25 01:59:09 +000067 .. attribute:: denominator
Christian Heimes072c0f12008-01-03 23:01:04 +000068
Benjamin Petersone41251e2008-04-25 01:59:09 +000069 Abstract.
Christian Heimes072c0f12008-01-03 23:01:04 +000070
71
72.. class:: Integral
73
Georg Brandl1e1134a2013-04-14 11:58:54 +020074 Subtypes :class:`Rational` and adds a conversion to :class:`int`. Provides
75 defaults for :func:`float`, :attr:`~Rational.numerator`, and
76 :attr:`~Rational.denominator`. Adds abstract methods for ``**`` and
77 bit-string operations: ``<<``, ``>>``, ``&``, ``^``, ``|``, ``~``.
Christian Heimes7b3ce6a2008-01-31 14:31:45 +000078
79
80Notes for type implementors
81---------------------------
82
83Implementors should be careful to make equal numbers equal and hash
84them to the same values. This may be subtle if there are two different
Christian Heimes3feef612008-02-11 06:19:17 +000085extensions of the real numbers. For example, :class:`fractions.Fraction`
Christian Heimes7b3ce6a2008-01-31 14:31:45 +000086implements :func:`hash` as follows::
87
88 def __hash__(self):
89 if self.denominator == 1:
90 # Get integers right.
91 return hash(self.numerator)
92 # Expensive check, but definitely correct.
93 if self == float(self):
94 return hash(float(self))
95 else:
96 # Use tuple's hash to avoid a high collision rate on
97 # simple fractions.
98 return hash((self.numerator, self.denominator))
99
100
101Adding More Numeric ABCs
102~~~~~~~~~~~~~~~~~~~~~~~~
103
104There are, of course, more possible ABCs for numbers, and this would
105be a poor hierarchy if it precluded the possibility of adding
106those. You can add ``MyFoo`` between :class:`Complex` and
107:class:`Real` with::
108
109 class MyFoo(Complex): ...
110 MyFoo.register(Real)
111
112
Ethan Furmanb0049432014-11-26 21:15:35 -0800113.. _implementing-the-arithmetic-operations:
114
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000115Implementing the arithmetic operations
116~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
117
118We want to implement the arithmetic operations so that mixed-mode
119operations either call an implementation whose author knew about the
120types of both arguments, or convert both to the nearest built in type
121and do the operation there. For subtypes of :class:`Integral`, this
122means that :meth:`__add__` and :meth:`__radd__` should be defined as::
123
124 class MyIntegral(Integral):
125
126 def __add__(self, other):
127 if isinstance(other, MyIntegral):
128 return do_my_adding_stuff(self, other)
129 elif isinstance(other, OtherTypeIKnowAbout):
130 return do_my_other_adding_stuff(self, other)
131 else:
132 return NotImplemented
133
134 def __radd__(self, other):
135 if isinstance(other, MyIntegral):
136 return do_my_adding_stuff(other, self)
137 elif isinstance(other, OtherTypeIKnowAbout):
138 return do_my_other_adding_stuff(other, self)
139 elif isinstance(other, Integral):
140 return int(other) + int(self)
141 elif isinstance(other, Real):
142 return float(other) + float(self)
143 elif isinstance(other, Complex):
144 return complex(other) + complex(self)
145 else:
146 return NotImplemented
147
148
149There are 5 different cases for a mixed-type operation on subclasses
150of :class:`Complex`. I'll refer to all of the above code that doesn't
151refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as
152"boilerplate". ``a`` will be an instance of ``A``, which is a subtype
153of :class:`Complex` (``a : A <: Complex``), and ``b : B <:
154Complex``. I'll consider ``a + b``:
155
156 1. If ``A`` defines an :meth:`__add__` which accepts ``b``, all is
157 well.
158 2. If ``A`` falls back to the boilerplate code, and it were to
159 return a value from :meth:`__add__`, we'd miss the possibility
160 that ``B`` defines a more intelligent :meth:`__radd__`, so the
161 boilerplate should return :const:`NotImplemented` from
162 :meth:`__add__`. (Or ``A`` may not implement :meth:`__add__` at
163 all.)
164 3. Then ``B``'s :meth:`__radd__` gets a chance. If it accepts
165 ``a``, all is well.
166 4. If it falls back to the boilerplate, there are no more possible
167 methods to try, so this is where the default implementation
168 should live.
169 5. If ``B <: A``, Python tries ``B.__radd__`` before
170 ``A.__add__``. This is ok, because it was implemented with
171 knowledge of ``A``, so it can handle those instances before
172 delegating to :class:`Complex`.
173
Georg Brandl1f01deb2009-01-03 22:47:39 +0000174If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000175then the appropriate shared operation is the one involving the built
176in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b
177== b+a``.
178
179Because most of the operations on any given type will be very similar,
180it can be useful to define a helper function which generates the
181forward and reverse instances of any given operator. For example,
Christian Heimes3feef612008-02-11 06:19:17 +0000182:class:`fractions.Fraction` uses::
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000183
184 def _operator_fallbacks(monomorphic_operator, fallback_operator):
185 def forward(a, b):
Amaury Forgeot d'Arc6a00b642008-06-17 20:38:00 +0000186 if isinstance(b, (int, Fraction)):
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000187 return monomorphic_operator(a, b)
188 elif isinstance(b, float):
189 return fallback_operator(float(a), b)
190 elif isinstance(b, complex):
191 return fallback_operator(complex(a), b)
192 else:
193 return NotImplemented
194 forward.__name__ = '__' + fallback_operator.__name__ + '__'
195 forward.__doc__ = monomorphic_operator.__doc__
196
197 def reverse(b, a):
Christian Heimes3feef612008-02-11 06:19:17 +0000198 if isinstance(a, Rational):
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000199 # Includes ints.
200 return monomorphic_operator(a, b)
201 elif isinstance(a, numbers.Real):
202 return fallback_operator(float(a), float(b))
203 elif isinstance(a, numbers.Complex):
204 return fallback_operator(complex(a), complex(b))
205 else:
206 return NotImplemented
207 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
208 reverse.__doc__ = monomorphic_operator.__doc__
209
210 return forward, reverse
211
212 def _add(a, b):
213 """a + b"""
Christian Heimes3feef612008-02-11 06:19:17 +0000214 return Fraction(a.numerator * b.denominator +
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000215 b.numerator * a.denominator,
216 a.denominator * b.denominator)
217
218 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
219
Christian Heimesf75b2902008-03-16 17:29:44 +0000220 # ...