future.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # Copyright 2015 gRPC authors.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """A Future interface.
  15. Python doesn't have a Future interface in its standard library. In the absence
  16. of such a standard, three separate, incompatible implementations
  17. (concurrent.futures.Future, ndb.Future, and asyncio.Future) have appeared. This
  18. interface attempts to be as compatible as possible with
  19. concurrent.futures.Future. From ndb.Future it adopts a traceback-object accessor
  20. method.
  21. Unlike the concrete and implemented Future classes listed above, the Future
  22. class defined in this module is an entirely abstract interface that anyone may
  23. implement and use.
  24. The one known incompatibility between this interface and the interface of
  25. concurrent.futures.Future is that this interface defines its own CancelledError
  26. and TimeoutError exceptions rather than raising the implementation-private
  27. concurrent.futures._base.CancelledError and the
  28. built-in-but-only-in-3.3-and-later TimeoutError.
  29. """
  30. import abc
  31. class TimeoutError(Exception):
  32. """Indicates that a particular call timed out."""
  33. class CancelledError(Exception):
  34. """Indicates that the computation underlying a Future was cancelled."""
  35. class Future(abc.ABC):
  36. """A representation of a computation in another control flow.
  37. Computations represented by a Future may be yet to be begun, may be ongoing,
  38. or may have already completed.
  39. """
  40. # NOTE(nathaniel): This isn't the return type that I would want to have if it
  41. # were up to me. Were this interface being written from scratch, the return
  42. # type of this method would probably be a sum type like:
  43. #
  44. # NOT_COMMENCED
  45. # COMMENCED_AND_NOT_COMPLETED
  46. # PARTIAL_RESULT<Partial_Result_Type>
  47. # COMPLETED<Result_Type>
  48. # UNCANCELLABLE
  49. # NOT_IMMEDIATELY_DETERMINABLE
  50. @abc.abstractmethod
  51. def cancel(self):
  52. """Attempts to cancel the computation.
  53. This method does not block.
  54. Returns:
  55. True if the computation has not yet begun, will not be allowed to take
  56. place, and determination of both was possible without blocking. False
  57. under all other circumstances including but not limited to the
  58. computation's already having begun, the computation's already having
  59. finished, and the computation's having been scheduled for execution on a
  60. remote system for which a determination of whether or not it commenced
  61. before being cancelled cannot be made without blocking.
  62. """
  63. raise NotImplementedError()
  64. # NOTE(nathaniel): Here too this isn't the return type that I'd want this
  65. # method to have if it were up to me. I think I'd go with another sum type
  66. # like:
  67. #
  68. # NOT_CANCELLED (this object's cancel method hasn't been called)
  69. # NOT_COMMENCED
  70. # COMMENCED_AND_NOT_COMPLETED
  71. # PARTIAL_RESULT<Partial_Result_Type>
  72. # COMPLETED<Result_Type>
  73. # UNCANCELLABLE
  74. # NOT_IMMEDIATELY_DETERMINABLE
  75. #
  76. # Notice how giving the cancel method the right semantics obviates most
  77. # reasons for this method to exist.
  78. @abc.abstractmethod
  79. def cancelled(self):
  80. """Describes whether the computation was cancelled.
  81. This method does not block.
  82. Returns:
  83. True if the computation was cancelled any time before its result became
  84. immediately available. False under all other circumstances including but
  85. not limited to this object's cancel method not having been called and
  86. the computation's result having become immediately available.
  87. """
  88. raise NotImplementedError()
  89. @abc.abstractmethod
  90. def running(self):
  91. """Describes whether the computation is taking place.
  92. This method does not block.
  93. Returns:
  94. True if the computation is scheduled to take place in the future or is
  95. taking place now, or False if the computation took place in the past or
  96. was cancelled.
  97. """
  98. raise NotImplementedError()
  99. # NOTE(nathaniel): These aren't quite the semantics I'd like here either. I
  100. # would rather this only returned True in cases in which the underlying
  101. # computation completed successfully. A computation's having been cancelled
  102. # conflicts with considering that computation "done".
  103. @abc.abstractmethod
  104. def done(self):
  105. """Describes whether the computation has taken place.
  106. This method does not block.
  107. Returns:
  108. True if the computation is known to have either completed or have been
  109. unscheduled or interrupted. False if the computation may possibly be
  110. executing or scheduled to execute later.
  111. """
  112. raise NotImplementedError()
  113. @abc.abstractmethod
  114. def result(self, timeout=None):
  115. """Accesses the outcome of the computation or raises its exception.
  116. This method may return immediately or may block.
  117. Args:
  118. timeout: The length of time in seconds to wait for the computation to
  119. finish or be cancelled, or None if this method should block until the
  120. computation has finished or is cancelled no matter how long that takes.
  121. Returns:
  122. The return value of the computation.
  123. Raises:
  124. TimeoutError: If a timeout value is passed and the computation does not
  125. terminate within the allotted time.
  126. CancelledError: If the computation was cancelled.
  127. Exception: If the computation raised an exception, this call will raise
  128. the same exception.
  129. """
  130. raise NotImplementedError()
  131. @abc.abstractmethod
  132. def exception(self, timeout=None):
  133. """Return the exception raised by the computation.
  134. This method may return immediately or may block.
  135. Args:
  136. timeout: The length of time in seconds to wait for the computation to
  137. terminate or be cancelled, or None if this method should block until
  138. the computation is terminated or is cancelled no matter how long that
  139. takes.
  140. Returns:
  141. The exception raised by the computation, or None if the computation did
  142. not raise an exception.
  143. Raises:
  144. TimeoutError: If a timeout value is passed and the computation does not
  145. terminate within the allotted time.
  146. CancelledError: If the computation was cancelled.
  147. """
  148. raise NotImplementedError()
  149. @abc.abstractmethod
  150. def traceback(self, timeout=None):
  151. """Access the traceback of the exception raised by the computation.
  152. This method may return immediately or may block.
  153. Args:
  154. timeout: The length of time in seconds to wait for the computation to
  155. terminate or be cancelled, or None if this method should block until
  156. the computation is terminated or is cancelled no matter how long that
  157. takes.
  158. Returns:
  159. The traceback of the exception raised by the computation, or None if the
  160. computation did not raise an exception.
  161. Raises:
  162. TimeoutError: If a timeout value is passed and the computation does not
  163. terminate within the allotted time.
  164. CancelledError: If the computation was cancelled.
  165. """
  166. raise NotImplementedError()
  167. @abc.abstractmethod
  168. def add_done_callback(self, fn):
  169. """Adds a function to be called at completion of the computation.
  170. The callback will be passed this Future object describing the outcome of
  171. the computation.
  172. If the computation has already completed, the callback will be called
  173. immediately.
  174. Args:
  175. fn: A callable taking this Future object as its single parameter.
  176. """
  177. raise NotImplementedError()