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. See also :ref:`numeric-hash`.
94
95
96 Adding More Numeric ABCs
97 ~~~~~~~~~~~~~~~~~~~~~~~~
98
99 There are, of course, more possible ABCs for numbers, and this would
100 be a poor hierarchy if it precluded the possibility of adding
101 those. You can add ``MyFoo`` between :class:`Complex` and
102 :class:`Real` with::
103
104 class MyFoo(Complex): ...
105 MyFoo.register(Real)
106
107
108 .. _implementing-the-arithmetic-operations:
109
110 Implementing the arithmetic operations
111 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
112
113 We want to implement the arithmetic operations so that mixed-mode
114 operations either call an implementation whose author knew about the
115 types of both arguments, or convert both to the nearest built in type
116 and do the operation there. For subtypes of :class:`Integral`, this
117 means that :meth:`~object.__add__` and :meth:`~object.__radd__` should be
118 defined as::
119
120 class MyIntegral(Integral):
121
122 def __add__(self, other):
123 if isinstance(other, MyIntegral):
124 return do_my_adding_stuff(self, other)
125 elif isinstance(other, OtherTypeIKnowAbout):
126 return do_my_other_adding_stuff(self, other)
127 else:
128 return NotImplemented
129
130 def __radd__(self, other):
131 if isinstance(other, MyIntegral):
132 return do_my_adding_stuff(other, self)
133 elif isinstance(other, OtherTypeIKnowAbout):
134 return do_my_other_adding_stuff(other, self)
135 elif isinstance(other, Integral):
136 return int(other) + int(self)
137 elif isinstance(other, Real):
138 return float(other) + float(self)
139 elif isinstance(other, Complex):
140 return complex(other) + complex(self)
141 else:
142 return NotImplemented
143
144
145 There are 5 different cases for a mixed-type operation on subclasses
146 of :class:`Complex`. I'll refer to all of the above code that doesn't
147 refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as
148 "boilerplate". ``a`` will be an instance of ``A``, which is a subtype
149 of :class:`Complex` (``a : A <: Complex``), and ``b : B <:
150 Complex``. I'll consider ``a + b``:
151
152 1. If ``A`` defines an :meth:`~object.__add__` which accepts ``b``, all is
153 well.
154 2. If ``A`` falls back to the boilerplate code, and it were to
155 return a value from :meth:`~object.__add__`, we'd miss the possibility
156 that ``B`` defines a more intelligent :meth:`~object.__radd__`, so the
157 boilerplate should return :data:`NotImplemented` from
158 :meth:`!__add__`. (Or ``A`` may not implement :meth:`!__add__` at
159 all.)
160 3. Then ``B``'s :meth:`~object.__radd__` gets a chance. If it accepts
161 ``a``, all is well.
162 4. If it falls back to the boilerplate, there are no more possible
163 methods to try, so this is where the default implementation
164 should live.
165 5. If ``B <: A``, Python tries ``B.__radd__`` before
166 ``A.__add__``. This is ok, because it was implemented with
167 knowledge of ``A``, so it can handle those instances before
168 delegating to :class:`Complex`.
169
170 If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
171 then the appropriate shared operation is the one involving the built
172 in :class:`complex`, and both :meth:`~object.__radd__` s land there, so ``a+b
173 == b+a``.
174
175 Because most of the operations on any given type will be very similar,
176 it can be useful to define a helper function which generates the
177 forward and reverse instances of any given operator. For example,
178 :class:`fractions.Fraction` uses::
179
180 def _operator_fallbacks(monomorphic_operator, fallback_operator):
181 def forward(a, b):
182 if isinstance(b, (int, Fraction)):
183 return monomorphic_operator(a, b)
184 elif isinstance(b, float):
185 return fallback_operator(float(a), b)
186 elif isinstance(b, complex):
187 return fallback_operator(complex(a), b)
188 else:
189 return NotImplemented
190 forward.__name__ = '__' + fallback_operator.__name__ + '__'
191 forward.__doc__ = monomorphic_operator.__doc__
192
193 def reverse(b, a):
194 if isinstance(a, Rational):
195 # Includes ints.
196 return monomorphic_operator(a, b)
197 elif isinstance(a, Real):
198 return fallback_operator(float(a), float(b))
199 elif isinstance(a, Complex):
200 return fallback_operator(complex(a), complex(b))
201 else:
202 return NotImplemented
203 reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
204 reverse.__doc__ = monomorphic_operator.__doc__
205
206 return forward, reverse
207
208 def _add(a, b):
209 """a + b"""
210 return Fraction(a.numerator * b.denominator +
211 b.numerator * a.denominator,
212 a.denominator * b.denominator)
213
214 __add__, __radd__ = _operator_fallbacks(_add, operator.add)
215
216 # ...