numbers.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Abstract Base Classes (ABCs) for numbers, according to PEP 3141.
  4. TODO: Fill out more detailed documentation on the operators."""
  5. ############ Maintenance notes #########################################
  6. #
  7. # ABCs are different from other standard library modules in that they
  8. # specify compliance tests. In general, once an ABC has been published,
  9. # new methods (either abstract or concrete) cannot be added.
  10. #
  11. # Though classes that inherit from an ABC would automatically receive a
  12. # new mixin method, registered classes would become non-compliant and
  13. # violate the contract promised by ``isinstance(someobj, SomeABC)``.
  14. #
  15. # Though irritating, the correct procedure for adding new abstract or
  16. # mixin methods is to create a new ABC as a subclass of the previous
  17. # ABC.
  18. #
  19. # Because they are so hard to change, new ABCs should have their APIs
  20. # carefully thought through prior to publication.
  21. #
  22. # Since ABCMeta only checks for the presence of methods, it is possible
  23. # to alter the signature of a method by adding optional arguments
  24. # or changing parameter names. This is still a bit dubious but at
  25. # least it won't cause isinstance() to return an incorrect result.
  26. #
  27. #
  28. #######################################################################
  29. from abc import ABCMeta, abstractmethod
  30. __all__ = ["Number", "Complex", "Real", "Rational", "Integral"]
  31. class Number(metaclass=ABCMeta):
  32. """All numbers inherit from this class.
  33. If you just want to check if an argument x is a number, without
  34. caring what kind, use isinstance(x, Number).
  35. """
  36. __slots__ = ()
  37. # Concrete numeric types must provide their own hash implementation
  38. __hash__ = None
  39. ## Notes on Decimal
  40. ## ----------------
  41. ## Decimal has all of the methods specified by the Real abc, but it should
  42. ## not be registered as a Real because decimals do not interoperate with
  43. ## binary floats (i.e. Decimal('3.14') + 2.71828 is undefined). But,
  44. ## abstract reals are expected to interoperate (i.e. R1 + R2 should be
  45. ## expected to work if R1 and R2 are both Reals).
  46. class Complex(Number):
  47. """Complex defines the operations that work on the builtin complex type.
  48. In short, those are: a conversion to complex, .real, .imag, +, -,
  49. *, /, **, abs(), .conjugate, ==, and !=.
  50. If it is given heterogeneous arguments, and doesn't have special
  51. knowledge about them, it should fall back to the builtin complex
  52. type as described below.
  53. """
  54. __slots__ = ()
  55. @abstractmethod
  56. def __complex__(self):
  57. """Return a builtin complex instance. Called for complex(self)."""
  58. def __bool__(self):
  59. """True if self != 0. Called for bool(self)."""
  60. return self != 0
  61. @property
  62. @abstractmethod
  63. def real(self):
  64. """Retrieve the real component of this number.
  65. This should subclass Real.
  66. """
  67. raise NotImplementedError
  68. @property
  69. @abstractmethod
  70. def imag(self):
  71. """Retrieve the imaginary component of this number.
  72. This should subclass Real.
  73. """
  74. raise NotImplementedError
  75. @abstractmethod
  76. def __add__(self, other):
  77. """self + other"""
  78. raise NotImplementedError
  79. @abstractmethod
  80. def __radd__(self, other):
  81. """other + self"""
  82. raise NotImplementedError
  83. @abstractmethod
  84. def __neg__(self):
  85. """-self"""
  86. raise NotImplementedError
  87. @abstractmethod
  88. def __pos__(self):
  89. """+self"""
  90. raise NotImplementedError
  91. def __sub__(self, other):
  92. """self - other"""
  93. return self + -other
  94. def __rsub__(self, other):
  95. """other - self"""
  96. return -self + other
  97. @abstractmethod
  98. def __mul__(self, other):
  99. """self * other"""
  100. raise NotImplementedError
  101. @abstractmethod
  102. def __rmul__(self, other):
  103. """other * self"""
  104. raise NotImplementedError
  105. @abstractmethod
  106. def __truediv__(self, other):
  107. """self / other: Should promote to float when necessary."""
  108. raise NotImplementedError
  109. @abstractmethod
  110. def __rtruediv__(self, other):
  111. """other / self"""
  112. raise NotImplementedError
  113. @abstractmethod
  114. def __pow__(self, exponent):
  115. """self ** exponent; should promote to float or complex when necessary."""
  116. raise NotImplementedError
  117. @abstractmethod
  118. def __rpow__(self, base):
  119. """base ** self"""
  120. raise NotImplementedError
  121. @abstractmethod
  122. def __abs__(self):
  123. """Returns the Real distance from 0. Called for abs(self)."""
  124. raise NotImplementedError
  125. @abstractmethod
  126. def conjugate(self):
  127. """(x+y*i).conjugate() returns (x-y*i)."""
  128. raise NotImplementedError
  129. @abstractmethod
  130. def __eq__(self, other):
  131. """self == other"""
  132. raise NotImplementedError
  133. Complex.register(complex)
  134. class Real(Complex):
  135. """To Complex, Real adds the operations that work on real numbers.
  136. In short, those are: a conversion to float, trunc(), divmod,
  137. %, <, <=, >, and >=.
  138. Real also provides defaults for the derived operations.
  139. """
  140. __slots__ = ()
  141. @abstractmethod
  142. def __float__(self):
  143. """Any Real can be converted to a native float object.
  144. Called for float(self)."""
  145. raise NotImplementedError
  146. @abstractmethod
  147. def __trunc__(self):
  148. """trunc(self): Truncates self to an Integral.
  149. Returns an Integral i such that:
  150. * i > 0 iff self > 0;
  151. * abs(i) <= abs(self);
  152. * for any Integral j satisfying the first two conditions,
  153. abs(i) >= abs(j) [i.e. i has "maximal" abs among those].
  154. i.e. "truncate towards 0".
  155. """
  156. raise NotImplementedError
  157. @abstractmethod
  158. def __floor__(self):
  159. """Finds the greatest Integral <= self."""
  160. raise NotImplementedError
  161. @abstractmethod
  162. def __ceil__(self):
  163. """Finds the least Integral >= self."""
  164. raise NotImplementedError
  165. @abstractmethod
  166. def __round__(self, ndigits=None):
  167. """Rounds self to ndigits decimal places, defaulting to 0.
  168. If ndigits is omitted or None, returns an Integral, otherwise
  169. returns a Real. Rounds half toward even.
  170. """
  171. raise NotImplementedError
  172. def __divmod__(self, other):
  173. """divmod(self, other): The pair (self // other, self % other).
  174. Sometimes this can be computed faster than the pair of
  175. operations.
  176. """
  177. return (self // other, self % other)
  178. def __rdivmod__(self, other):
  179. """divmod(other, self): The pair (other // self, other % self).
  180. Sometimes this can be computed faster than the pair of
  181. operations.
  182. """
  183. return (other // self, other % self)
  184. @abstractmethod
  185. def __floordiv__(self, other):
  186. """self // other: The floor() of self/other."""
  187. raise NotImplementedError
  188. @abstractmethod
  189. def __rfloordiv__(self, other):
  190. """other // self: The floor() of other/self."""
  191. raise NotImplementedError
  192. @abstractmethod
  193. def __mod__(self, other):
  194. """self % other"""
  195. raise NotImplementedError
  196. @abstractmethod
  197. def __rmod__(self, other):
  198. """other % self"""
  199. raise NotImplementedError
  200. @abstractmethod
  201. def __lt__(self, other):
  202. """self < other
  203. < on Reals defines a total ordering, except perhaps for NaN."""
  204. raise NotImplementedError
  205. @abstractmethod
  206. def __le__(self, other):
  207. """self <= other"""
  208. raise NotImplementedError
  209. # Concrete implementations of Complex abstract methods.
  210. def __complex__(self):
  211. """complex(self) == complex(float(self), 0)"""
  212. return complex(float(self))
  213. @property
  214. def real(self):
  215. """Real numbers are their real component."""
  216. return +self
  217. @property
  218. def imag(self):
  219. """Real numbers have no imaginary component."""
  220. return 0
  221. def conjugate(self):
  222. """Conjugate is a no-op for Reals."""
  223. return +self
  224. Real.register(float)
  225. class Rational(Real):
  226. """.numerator and .denominator should be in lowest terms."""
  227. __slots__ = ()
  228. @property
  229. @abstractmethod
  230. def numerator(self):
  231. raise NotImplementedError
  232. @property
  233. @abstractmethod
  234. def denominator(self):
  235. raise NotImplementedError
  236. # Concrete implementation of Real's conversion to float.
  237. def __float__(self):
  238. """float(self) = self.numerator / self.denominator
  239. It's important that this conversion use the integer's "true"
  240. division rather than casting one side to float before dividing
  241. so that ratios of huge integers convert without overflowing.
  242. """
  243. return int(self.numerator) / int(self.denominator)
  244. class Integral(Rational):
  245. """Integral adds methods that work on integral numbers.
  246. In short, these are conversion to int, pow with modulus, and the
  247. bit-string operations.
  248. """
  249. __slots__ = ()
  250. @abstractmethod
  251. def __int__(self):
  252. """int(self)"""
  253. raise NotImplementedError
  254. def __index__(self):
  255. """Called whenever an index is needed, such as in slicing"""
  256. return int(self)
  257. @abstractmethod
  258. def __pow__(self, exponent, modulus=None):
  259. """self ** exponent % modulus, but maybe faster.
  260. Accept the modulus argument if you want to support the
  261. 3-argument version of pow(). Raise a TypeError if exponent < 0
  262. or any argument isn't Integral. Otherwise, just implement the
  263. 2-argument version described in Complex.
  264. """
  265. raise NotImplementedError
  266. @abstractmethod
  267. def __lshift__(self, other):
  268. """self << other"""
  269. raise NotImplementedError
  270. @abstractmethod
  271. def __rlshift__(self, other):
  272. """other << self"""
  273. raise NotImplementedError
  274. @abstractmethod
  275. def __rshift__(self, other):
  276. """self >> other"""
  277. raise NotImplementedError
  278. @abstractmethod
  279. def __rrshift__(self, other):
  280. """other >> self"""
  281. raise NotImplementedError
  282. @abstractmethod
  283. def __and__(self, other):
  284. """self & other"""
  285. raise NotImplementedError
  286. @abstractmethod
  287. def __rand__(self, other):
  288. """other & self"""
  289. raise NotImplementedError
  290. @abstractmethod
  291. def __xor__(self, other):
  292. """self ^ other"""
  293. raise NotImplementedError
  294. @abstractmethod
  295. def __rxor__(self, other):
  296. """other ^ self"""
  297. raise NotImplementedError
  298. @abstractmethod
  299. def __or__(self, other):
  300. """self | other"""
  301. raise NotImplementedError
  302. @abstractmethod
  303. def __ror__(self, other):
  304. """other | self"""
  305. raise NotImplementedError
  306. @abstractmethod
  307. def __invert__(self):
  308. """~self"""
  309. raise NotImplementedError
  310. # Concrete implementations of Rational and Real abstract methods.
  311. def __float__(self):
  312. """float(self) == float(int(self))"""
  313. return float(int(self))
  314. @property
  315. def numerator(self):
  316. """Integers are their own numerators."""
  317. return +self
  318. @property
  319. def denominator(self):
  320. """Integers have a denominator of 1."""
  321. return 1
  322. Integral.register(int)