Debian Codegraph @

Doc/library/numbers.rst

raw
1 :mod:`!numbers` --- Numeric abstract base classes
2 =================================================
3
4 .. module:: numbers
5 :synopsis: Numeric abstract base classes (Complex, Real, Integral, etc.).
6
7 **Source code:** :source:`Lib/numbers.py`
8
9 --------------
10
11 The :mod:`!numbers` module (:pep:`3141`) defines a hierarchy of numeric
12 :term:`abstract base classes <abstract base class>` which progressively define
13 more operations. None of the types defined in this module are intended to be instantiated.
14
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
22 The numeric tower
23 -----------------
24
25 .. class:: Complex
26
27 Subclasses of this type describe complex numbers and include the operations
28 that work on the built-in :class:`complex` type. These are: conversions to
29 :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``,
30 ``-``, ``*``, ``/``, ``**``, :func:`abs`, :meth:`conjugate`, ``==``, and
31 ``!=``. All except ``-`` and ``!=`` are abstract.
32
33 .. attribute:: real
34
35 Abstract. Retrieves the real component of this number.
36
37 .. attribute:: imag
38
39 Abstract. Retrieves the imaginary component of this number.
40
41 .. method:: conjugate()
42 :abstractmethod:
43
44 Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate()
45 == (1-3j)``.
46
47 .. class:: Real
48
49 To :class:`Complex`, :class:`!Real` adds the operations that work on real
50 numbers.
51
52 In short, those are: a conversion to :class:`float`, :func:`math.trunc`,
53 :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``,
54 ``%``, ``<``, ``<=``, ``>``, and ``>=``.
55
56 Real also provides defaults for :func:`complex`, :attr:`~Complex.real`,
57 :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`.
58
59
60 .. class:: Rational
61
62 Subtypes :class:`Real` and adds :attr:`~Rational.numerator` and
63 :attr:`~Rational.denominator` properties. It also provides a default for
64 :func:`float`.
65
66 The :attr:`~Rational.numerator` and :attr:`~Rational.denominator` values
67 should be instances of :class:`Integral` and should be in lowest terms with
68 :attr:`~Rational.denominator` positive.
69
70 .. attribute:: numerator
71
72 Abstract. The numerator of this rational number.
73
74 .. attribute:: denominator
75
76 Abstract. The denominator of this rational number.
77
78
79 .. class:: Integral
80
81 Subtypes :class:`Rational` and adds a conversion to :class:`int`. Provides
82 defaults for :func:`float`, :attr:`~Rational.numerator`, and
83 :attr:`~Rational.denominator`. Adds abstract methods for :func:`pow` with
84 modulus and bit-string operations: ``<<``, ``>>``, ``&``, ``^``, ``|``,
85 ``~``.
86
87
88 Notes for type implementers
89 ---------------------------
90
91 Implementers should be careful to make equal numbers equal and hash
92 them to the same values. This may be subtle if there are two different
93 extensions of the real numbers. For example, :class:`fractions.Fraction`
94 implements :func:`hash` as follows::
95
96 def __hash__(self):
97 if self.denominator == 1:
98 # Get integers right.
99 return hash(self.numerator)
100 # Expensive check, but definitely correct.
101 if self == float(self):
102 return hash(float(self))
103 else:
104 # Use tuple's hash to avoid a high collision rate on
105 # simple fractions.
106 return hash((self.numerator, self.denominator))
107
108
109 Adding More Numeric ABCs
110 ~~~~~~~~~~~~~~~~~~~~~~~~
111
112 There are, of course, more possible ABCs for numbers, and this would
113 be a poor hierarchy if it precluded the possibility of adding
114 those. You can add ``MyFoo`` between :class:`Complex` and
115 :class:`Real` with::
116
117 class MyFoo(Complex): ...
118 MyFoo.register(Real)
119
120
121 .. _implementing-the-arithmetic-operations:
122
123 Implementing the arithmetic operations
124 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125
126 We want to implement the arithmetic operations so that mixed-mode
127 operations either call an implementation whose author knew about the
128 types of both arguments, or convert both to the nearest built in type
129 and do the operation there. For subtypes of :class:`Integral`, this
130 means that :meth:`~object.__add__` and :meth:`~object.__radd__` should be
131 defined as::
132
133 class MyIntegral(Integral):
134
135 def __add__(self, other):
136 if isinstance(other, MyIntegral):
137 return do_my_adding_stuff(self, other)
138 elif isinstance(other, OtherTypeIKnowAbout):
139 return do_my_other_adding_stuff(self, other)
140 else:
141 return NotImplemented
142
143 def __radd__(self, other):
144 if isinstance(other, MyIntegral):
145 return do_my_adding_stuff(other, self)
146 elif isinstance(other, OtherTypeIKnowAbout):
147 return do_my_other_adding_stuff(other, self)
148 elif isinstance(other, Integral):
149 return int(other) + int(self)
150 elif isinstance(other, Real):
151 return float(other) + float(self)
152 elif isinstance(other, Complex):
153 return complex(other) + complex(self)
154 else:
155 return NotImplemented
156
157
158 There are 5 different cases for a mixed-type operation on subclasses
159 of :class:`Complex`. I'll refer to all of the above code that doesn't
160 refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as
161 "boilerplate". ``a`` will be an instance of ``A``, which is a subtype
162 of :class:`Complex` (``a : A <: Complex``), and ``b : B <:
163 Complex``. I'll consider ``a + b``:
164
165 1. If ``A`` defines an :meth:`~object.__add__` which accepts ``b``, all is
166 well.
167 2. If ``A`` falls back to the boilerplate code, and it were to
168 return a value from :meth:`~object.__add__`, we'd miss the possibility
169 that ``B`` defines a more intelligent :meth:`~object.__radd__`, so the
170 boilerplate should return :data:`NotImplemented` from
171 :meth:`!__add__`. (Or ``A`` may not implement :meth:`!__add__` at
172 all.)
173 3. Then ``B``'s :meth:`~object.__radd__` gets a chance. If it accepts
174 ``a``, all is well.
175 4. If it falls back to the boilerplate, there are no more possible
176 methods to try, so this is where the default implementation
177 should live.
178 5. If ``B <: A``, Python tries ``B.__radd__`` before
179 ``A.__add__``. This is ok, because it was implemented with
180 knowledge of ``A``, so it can handle those instances before
181 delegating to :class:`Complex`.
182
183 If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
184 then the appropriate shared operation is the one involving the built
185 in :class:`complex`, and both :meth:`~object.__radd__` s land there, so ``a+b
186 == b+a``.
187
188 Because most of the operations on any given type will be very similar,
189 it can be useful to define a helper function which generates the
190 forward and reverse instances of any given operator. For example,
191 :class:`fractions.Fraction` uses::
192
193 def _operator_fallbacks(monomorphic_operator, fallback_operator):
194 def forward(a, b):
195 if isinstance(b, (int, Fraction)):
196 return monomorphic_operator(a, b)
197 elif isinstance(b, float):
198 return fallback_operator(float(a), b)
199 elif isinstance(b, complex):
200 return fallback_operator(complex(a), b)
201 else:
202 return NotImplemented
203 forward.__name__ = '__' + fallback_operator.__name__ + '__'
204 forward.__doc__ = monomorphic_operator.__doc__
205
206 def reverse(b, a):
207 if isinstance(a, Rational):
208 # Includes ints.
209 return monomorphic_operator(a, b)
210 elif isinstance(a, Real):
211 return fallback_operator(float(a), float(b))
212 elif isinstance(a, Complex):
213 return fallback_operator(complex(a), complex(b))
214 else:
215 return NotImplemented
216 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
217 reverse.__doc__ = monomorphic_operator.__doc__
218
219 return forward, reverse
220
221 def _add(a, b):
222 """a + b"""
223 return Fraction(a.numerator * b.denominator +
224 b.numerator * a.denominator,
225 a.denominator * b.denominator)
226
227 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
228
229 # ...