blob: 5d49f5eb96b7ad8ea148160c822df4010d5d78f3 [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007**Source code:** :source:`Lib/numbers.py`
8
9--------------
Christian Heimesfaf2f632008-01-06 16:59:19 +000010
Éric Araujofa088db2011-06-04 18:42:38 +020011The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric
12:term:`abstract base classes <abstract base class>` which progressively define
13more operations. None of the types defined in this module can be instantiated.
Christian Heimes072c0f12008-01-03 23:01:04 +000014
15
16.. class:: Number
17
18 The root of the numeric hierarchy. If you just want to check if an argument
19 *x* is a number, without caring what kind, use ``isinstance(x, Number)``.
20
21
Christian Heimes072c0f12008-01-03 23:01:04 +000022The numeric tower
23-----------------
24
25.. class:: Complex
26
27 Subclasses of this type describe complex numbers and include the operations
Georg Brandlc5605df2009-08-13 08:26:44 +000028 that work on the built-in :class:`complex` type. These are: conversions to
Christian Heimes072c0f12008-01-03 23:01:04 +000029 :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``,
30 ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
31 except ``-`` and ``!=`` are abstract.
32
Benjamin Petersone41251e2008-04-25 01:59:09 +000033 .. attribute:: real
Christian Heimes072c0f12008-01-03 23:01:04 +000034
Mark Dickinsonbc5f75c2010-05-05 21:55:11 +000035 Abstract. Retrieves the real component of this number.
Christian Heimes072c0f12008-01-03 23:01:04 +000036
Benjamin Petersone41251e2008-04-25 01:59:09 +000037 .. attribute:: imag
Christian Heimes072c0f12008-01-03 23:01:04 +000038
Mark Dickinsonbc5f75c2010-05-05 21:55:11 +000039 Abstract. Retrieves the imaginary component of this number.
Christian Heimes072c0f12008-01-03 23:01:04 +000040
Berker Peksag6e9d2e62015-12-08 12:14:50 +020041 .. abstractmethod:: conjugate()
Christian Heimes072c0f12008-01-03 23:01:04 +000042
Benjamin Petersone41251e2008-04-25 01:59:09 +000043 Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate()
44 == (1-3j)``.
Christian Heimes072c0f12008-01-03 23:01:04 +000045
46.. class:: Real
47
48 To :class:`Complex`, :class:`Real` adds the operations that work on real
49 numbers.
50
Benjamin Petersonab2b7162011-03-12 11:58:15 -060051 In short, those are: a conversion to :class:`float`, :func:`math.trunc`,
Robert Smallshire58a7da92020-10-01 18:30:08 +020052 :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`,
53 :func:`~Real.is_integer`, ``//``, ``%``, ``<``, ``<=``, ``>``, and ``>=``.
Christian Heimes072c0f12008-01-03 23:01:04 +000054
Georg Brandl1f01deb2009-01-03 22:47:39 +000055 Real also provides defaults for :func:`complex`, :attr:`~Complex.real`,
56 :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`.
Christian Heimes072c0f12008-01-03 23:01:04 +000057
Robert Smallshire58a7da92020-10-01 18:30:08 +020058 .. method:: is_integer()
59
60 Returns :const:`True` if this number has a finite and integral value,
61 otherwise :const:`False`. This is a default implementation which
62 relies on successful conversion to :class:`int`. It may be overridden
63 in subclasses (such as it is in :class:`float`) for better performance,
64 or to handle special values such as NaN which are not
65 convertible to :class:`int`.
66
67 .. versionadded:: 3.10
68
Christian Heimes072c0f12008-01-03 23:01:04 +000069
70.. class:: Rational
71
Christian Heimesf75b2902008-03-16 17:29:44 +000072 Subtypes :class:`Real` and adds
Georg Brandl1f01deb2009-01-03 22:47:39 +000073 :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which
Robert Smallshire58a7da92020-10-01 18:30:08 +020074 should be in lowest terms. With these, it provides defaults for
75 :func:`float` and :func:`~Real.is_integer`.
Christian Heimes072c0f12008-01-03 23:01:04 +000076
Benjamin Petersone41251e2008-04-25 01:59:09 +000077 .. attribute:: numerator
Christian Heimes072c0f12008-01-03 23:01:04 +000078
Benjamin Petersone41251e2008-04-25 01:59:09 +000079 Abstract.
Christian Heimes072c0f12008-01-03 23:01:04 +000080
Benjamin Petersone41251e2008-04-25 01:59:09 +000081 .. attribute:: denominator
Christian Heimes072c0f12008-01-03 23:01:04 +000082
Benjamin Petersone41251e2008-04-25 01:59:09 +000083 Abstract.
Christian Heimes072c0f12008-01-03 23:01:04 +000084
85
86.. class:: Integral
87
Georg Brandl1e1134a2013-04-14 11:58:54 +020088 Subtypes :class:`Rational` and adds a conversion to :class:`int`. Provides
Robert Smallshire58a7da92020-10-01 18:30:08 +020089 defaults for :func:`float`, :attr:`~Rational.numerator`,
90 :attr:`~Rational.denominator`, and :func:`~Real.is_integer`. Adds abstract
91 methods for ``**`` and bit-string operations: ``<<``, ``>>``, ``&``, ``^``,
92 ``|``, ``~``.
Christian Heimes7b3ce6a2008-01-31 14:31:45 +000093
94
95Notes for type implementors
96---------------------------
97
98Implementors should be careful to make equal numbers equal and hash
99them to the same values. This may be subtle if there are two different
Christian Heimes3feef612008-02-11 06:19:17 +0000100extensions of the real numbers. For example, :class:`fractions.Fraction`
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000101implements :func:`hash` as follows::
102
103 def __hash__(self):
104 if self.denominator == 1:
105 # Get integers right.
106 return hash(self.numerator)
107 # Expensive check, but definitely correct.
108 if self == float(self):
109 return hash(float(self))
110 else:
111 # Use tuple's hash to avoid a high collision rate on
112 # simple fractions.
113 return hash((self.numerator, self.denominator))
114
115
116Adding More Numeric ABCs
117~~~~~~~~~~~~~~~~~~~~~~~~
118
119There are, of course, more possible ABCs for numbers, and this would
120be a poor hierarchy if it precluded the possibility of adding
121those. You can add ``MyFoo`` between :class:`Complex` and
122:class:`Real` with::
123
124 class MyFoo(Complex): ...
125 MyFoo.register(Real)
126
127
Ethan Furmanb0049432014-11-26 21:15:35 -0800128.. _implementing-the-arithmetic-operations:
129
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000130Implementing the arithmetic operations
131~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
132
133We want to implement the arithmetic operations so that mixed-mode
134operations either call an implementation whose author knew about the
135types of both arguments, or convert both to the nearest built in type
136and do the operation there. For subtypes of :class:`Integral`, this
137means that :meth:`__add__` and :meth:`__radd__` should be defined as::
138
139 class MyIntegral(Integral):
140
141 def __add__(self, other):
142 if isinstance(other, MyIntegral):
143 return do_my_adding_stuff(self, other)
144 elif isinstance(other, OtherTypeIKnowAbout):
145 return do_my_other_adding_stuff(self, other)
146 else:
147 return NotImplemented
148
149 def __radd__(self, other):
150 if isinstance(other, MyIntegral):
151 return do_my_adding_stuff(other, self)
152 elif isinstance(other, OtherTypeIKnowAbout):
153 return do_my_other_adding_stuff(other, self)
154 elif isinstance(other, Integral):
155 return int(other) + int(self)
156 elif isinstance(other, Real):
157 return float(other) + float(self)
158 elif isinstance(other, Complex):
159 return complex(other) + complex(self)
160 else:
161 return NotImplemented
162
163
164There are 5 different cases for a mixed-type operation on subclasses
165of :class:`Complex`. I'll refer to all of the above code that doesn't
166refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as
167"boilerplate". ``a`` will be an instance of ``A``, which is a subtype
168of :class:`Complex` (``a : A <: Complex``), and ``b : B <:
169Complex``. I'll consider ``a + b``:
170
171 1. If ``A`` defines an :meth:`__add__` which accepts ``b``, all is
172 well.
173 2. If ``A`` falls back to the boilerplate code, and it were to
174 return a value from :meth:`__add__`, we'd miss the possibility
175 that ``B`` defines a more intelligent :meth:`__radd__`, so the
176 boilerplate should return :const:`NotImplemented` from
177 :meth:`__add__`. (Or ``A`` may not implement :meth:`__add__` at
178 all.)
179 3. Then ``B``'s :meth:`__radd__` gets a chance. If it accepts
180 ``a``, all is well.
181 4. If it falls back to the boilerplate, there are no more possible
182 methods to try, so this is where the default implementation
183 should live.
184 5. If ``B <: A``, Python tries ``B.__radd__`` before
185 ``A.__add__``. This is ok, because it was implemented with
186 knowledge of ``A``, so it can handle those instances before
187 delegating to :class:`Complex`.
188
Georg Brandl1f01deb2009-01-03 22:47:39 +0000189If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000190then the appropriate shared operation is the one involving the built
191in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b
192== b+a``.
193
194Because most of the operations on any given type will be very similar,
195it can be useful to define a helper function which generates the
196forward and reverse instances of any given operator. For example,
Christian Heimes3feef612008-02-11 06:19:17 +0000197:class:`fractions.Fraction` uses::
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000198
199 def _operator_fallbacks(monomorphic_operator, fallback_operator):
200 def forward(a, b):
Amaury Forgeot d'Arc6a00b642008-06-17 20:38:00 +0000201 if isinstance(b, (int, Fraction)):
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000202 return monomorphic_operator(a, b)
203 elif isinstance(b, float):
204 return fallback_operator(float(a), b)
205 elif isinstance(b, complex):
206 return fallback_operator(complex(a), b)
207 else:
208 return NotImplemented
209 forward.__name__ = '__' + fallback_operator.__name__ + '__'
210 forward.__doc__ = monomorphic_operator.__doc__
211
212 def reverse(b, a):
Christian Heimes3feef612008-02-11 06:19:17 +0000213 if isinstance(a, Rational):
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000214 # Includes ints.
215 return monomorphic_operator(a, b)
216 elif isinstance(a, numbers.Real):
217 return fallback_operator(float(a), float(b))
218 elif isinstance(a, numbers.Complex):
219 return fallback_operator(complex(a), complex(b))
220 else:
221 return NotImplemented
222 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
223 reverse.__doc__ = monomorphic_operator.__doc__
224
225 return forward, reverse
226
227 def _add(a, b):
228 """a + b"""
Christian Heimes3feef612008-02-11 06:19:17 +0000229 return Fraction(a.numerator * b.denominator +
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000230 b.numerator * a.denominator,
231 a.denominator * b.denominator)
232
233 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
234
Christian Heimesf75b2902008-03-16 17:29:44 +0000235 # ...