blob: 4a56f32c7745c96182d760024ceaddd70f7738fc [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""A Future class similar to the one in PEP 3148."""
2
Yury Selivanov6370f342017-12-10 18:36:12 -05003__all__ = (
4 'CancelledError', 'TimeoutError', 'InvalidStateError',
5 'Future', 'wrap_future', 'isfuture',
6)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07007
Yury Selivanova0c1ba62016-10-28 12:52:37 -04008import concurrent.futures
Yury Selivanovf23746a2018-01-22 19:11:18 -05009import contextvars
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070010import logging
Victor Stinner4c3c6992013-12-19 22:42:40 +010011import sys
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070012
Yury Selivanova0c1ba62016-10-28 12:52:37 -040013from . import base_futures
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070014from . import events
Andrew Svetlovf74ef452017-12-15 07:04:38 +020015from . import format_helpers
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070017
Yury Selivanova0c1ba62016-10-28 12:52:37 -040018CancelledError = base_futures.CancelledError
19InvalidStateError = base_futures.InvalidStateError
20TimeoutError = base_futures.TimeoutError
21isfuture = base_futures.isfuture
22
23
24_PENDING = base_futures._PENDING
25_CANCELLED = base_futures._CANCELLED
26_FINISHED = base_futures._FINISHED
27
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070028
29STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
30
31
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032class Future:
33 """This class is *almost* compatible with concurrent.futures.Future.
34
35 Differences:
36
Antoine Pitrou22b11282017-11-07 17:03:28 +010037 - This class is not thread-safe.
38
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039 - result() and exception() do not take a timeout argument and
40 raise an exception when the future isn't done yet.
41
42 - Callbacks registered with add_done_callback() are always called
Antoine Pitrou22b11282017-11-07 17:03:28 +010043 via the event loop's call_soon().
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044
45 - This class is not compatible with the wait() and as_completed()
46 methods in the concurrent.futures package.
47
48 (In Python 3.4 or later we may be able to unify the implementations.)
49 """
50
51 # Class variables serving as defaults for instance variables.
52 _state = _PENDING
53 _result = None
54 _exception = None
55 _loop = None
Victor Stinnerfe22e092014-12-04 23:00:13 +010056 _source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070057
Guido van Rossum1140a032016-09-09 12:54:54 -070058 # This field is used for a dual purpose:
59 # - Its presence is a marker to declare that a class implements
60 # the Future protocol (i.e. is intended to be duck-type compatible).
61 # The value must also be not-None, to enable a subclass to declare
62 # that it is not compatible by setting this to None.
63 # - It is set by __iter__() below so that Task._step() can tell
Andrew Svetlov88743422017-12-11 17:35:49 +020064 # the difference between
65 # `await Future()` or`yield from Future()` (correct) vs.
Guido van Rossum1140a032016-09-09 12:54:54 -070066 # `yield Future()` (incorrect).
67 _asyncio_future_blocking = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070068
Yury Selivanove0aef4f2017-12-25 16:16:10 -050069 __log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070070
71 def __init__(self, *, loop=None):
72 """Initialize the future.
73
Martin Panterc04fb562016-02-10 05:44:01 +000074 The optional event_loop argument allows explicitly setting the event
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070075 loop object used by the future. If it's not provided, the future uses
76 the default event loop.
77 """
78 if loop is None:
79 self._loop = events.get_event_loop()
80 else:
81 self._loop = loop
82 self._callbacks = []
Victor Stinner80f53aa2014-06-27 13:52:20 +020083 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020084 self._source_traceback = format_helpers.extract_stack(
85 sys._getframe(1))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070086
Yury Selivanova0c1ba62016-10-28 12:52:37 -040087 _repr_info = base_futures._future_repr_info
Victor Stinner313a9802014-07-29 12:58:23 +020088
89 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -050090 return '<{} {}>'.format(self.__class__.__name__,
91 ' '.join(self._repr_info()))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070092
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090093 def __del__(self):
Yury Selivanove0aef4f2017-12-25 16:16:10 -050094 if not self.__log_traceback:
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090095 # set_exception() was not called, or result() or exception()
96 # has consumed the exception
97 return
98 exc = self._exception
99 context = {
Yury Selivanov6370f342017-12-10 18:36:12 -0500100 'message':
101 f'{self.__class__.__name__} exception was never retrieved',
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900102 'exception': exc,
103 'future': self,
104 }
105 if self._source_traceback:
106 context['source_traceback'] = self._source_traceback
107 self._loop.call_exception_handler(context)
Victor Stinner4c3c6992013-12-19 22:42:40 +0100108
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500109 @property
110 def _log_traceback(self):
111 return self.__log_traceback
112
113 @_log_traceback.setter
114 def _log_traceback(self, val):
115 if bool(val):
116 raise ValueError('_log_traceback can only be set to False')
117 self.__log_traceback = False
118
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500119 def get_loop(self):
120 """Return the event loop the Future is bound to."""
121 return self._loop
122
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700123 def cancel(self):
124 """Cancel the future and schedule callbacks.
125
126 If the future is already done or cancelled, return False. Otherwise,
127 change the future's state to cancelled, schedule the callbacks and
128 return True.
129 """
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500130 self.__log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700131 if self._state != _PENDING:
132 return False
133 self._state = _CANCELLED
Yury Selivanov22feeb82018-01-24 11:31:01 -0500134 self.__schedule_callbacks()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700135 return True
136
Yury Selivanov22feeb82018-01-24 11:31:01 -0500137 def __schedule_callbacks(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700138 """Internal: Ask the event loop to call all callbacks.
139
140 The callbacks are scheduled to be called as soon as possible. Also
141 clears the callback list.
142 """
143 callbacks = self._callbacks[:]
144 if not callbacks:
145 return
146
147 self._callbacks[:] = []
Yury Selivanovf23746a2018-01-22 19:11:18 -0500148 for callback, ctx in callbacks:
149 self._loop.call_soon(callback, self, context=ctx)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700150
151 def cancelled(self):
152 """Return True if the future was cancelled."""
153 return self._state == _CANCELLED
154
155 # Don't implement running(); see http://bugs.python.org/issue18699
156
157 def done(self):
158 """Return True if the future is done.
159
160 Done means either that a result / exception are available, or that the
161 future was cancelled.
162 """
163 return self._state != _PENDING
164
165 def result(self):
166 """Return the result this future represents.
167
168 If the future has been cancelled, raises CancelledError. If the
169 future's result isn't yet available, raises InvalidStateError. If
170 the future is done and has an exception set, this exception is raised.
171 """
172 if self._state == _CANCELLED:
173 raise CancelledError
174 if self._state != _FINISHED:
175 raise InvalidStateError('Result is not ready.')
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500176 self.__log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700177 if self._exception is not None:
178 raise self._exception
179 return self._result
180
181 def exception(self):
182 """Return the exception that was set on this future.
183
184 The exception (or None if no exception was set) is returned only if
185 the future is done. If the future has been cancelled, raises
186 CancelledError. If the future isn't done yet, raises
187 InvalidStateError.
188 """
189 if self._state == _CANCELLED:
190 raise CancelledError
191 if self._state != _FINISHED:
192 raise InvalidStateError('Exception is not set.')
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500193 self.__log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194 return self._exception
195
Yury Selivanovf23746a2018-01-22 19:11:18 -0500196 def add_done_callback(self, fn, *, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700197 """Add a callback to be run when the future becomes done.
198
199 The callback is called with a single argument - the future object. If
200 the future is already done when this is called, the callback is
201 scheduled with call_soon.
202 """
203 if self._state != _PENDING:
Yury Selivanovf23746a2018-01-22 19:11:18 -0500204 self._loop.call_soon(fn, self, context=context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700205 else:
Yury Selivanovf23746a2018-01-22 19:11:18 -0500206 if context is None:
207 context = contextvars.copy_context()
208 self._callbacks.append((fn, context))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700209
210 # New method not in PEP 3148.
211
212 def remove_done_callback(self, fn):
213 """Remove all instances of a callback from the "call when done" list.
214
215 Returns the number of callbacks removed.
216 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500217 filtered_callbacks = [(f, ctx)
218 for (f, ctx) in self._callbacks
219 if f != fn]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700220 removed_count = len(self._callbacks) - len(filtered_callbacks)
221 if removed_count:
222 self._callbacks[:] = filtered_callbacks
223 return removed_count
224
225 # So-called internal methods (note: no set_running_or_notify_cancel()).
226
227 def set_result(self, result):
228 """Mark the future done and set its result.
229
230 If the future is already done when this method is called, raises
231 InvalidStateError.
232 """
233 if self._state != _PENDING:
234 raise InvalidStateError('{}: {!r}'.format(self._state, self))
235 self._result = result
236 self._state = _FINISHED
Yury Selivanov22feeb82018-01-24 11:31:01 -0500237 self.__schedule_callbacks()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700238
239 def set_exception(self, exception):
240 """Mark the future done and set an exception.
241
242 If the future is already done when this method is called, raises
243 InvalidStateError.
244 """
245 if self._state != _PENDING:
246 raise InvalidStateError('{}: {!r}'.format(self._state, self))
Victor Stinner95728982014-01-30 16:01:54 -0800247 if isinstance(exception, type):
248 exception = exception()
Yury Selivanov1bd03072016-03-02 11:03:28 -0500249 if type(exception) is StopIteration:
250 raise TypeError("StopIteration interacts badly with generators "
251 "and cannot be raised into a Future")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700252 self._exception = exception
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700253 self._state = _FINISHED
Yury Selivanov22feeb82018-01-24 11:31:01 -0500254 self.__schedule_callbacks()
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500255 self.__log_traceback = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700256
Yury Selivanov0cf16f92017-12-25 10:48:15 -0500257 def __await__(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700258 if not self.done():
Guido van Rossum1140a032016-09-09 12:54:54 -0700259 self._asyncio_future_blocking = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700260 yield self # This tells Task to wait for completion.
Yury Selivanov0cf16f92017-12-25 10:48:15 -0500261 if not self.done():
262 raise RuntimeError("await wasn't used with future")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700263 return self.result() # May raise too.
264
Yury Selivanov0cf16f92017-12-25 10:48:15 -0500265 __iter__ = __await__ # make compatible with 'yield from'.
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400266
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700267
Yury Selivanov01c521b2016-10-23 22:34:35 -0400268# Needed for testing purposes.
269_PyFuture = Future
270
271
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500272def _get_loop(fut):
273 # Tries to call Future.get_loop() if it's available.
274 # Otherwise fallbacks to using the old '_loop' property.
275 try:
276 get_loop = fut.get_loop
277 except AttributeError:
278 pass
279 else:
280 return get_loop()
281 return fut._loop
282
283
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500284def _set_result_unless_cancelled(fut, result):
285 """Helper setting the result only if the future was not cancelled."""
286 if fut.cancelled():
287 return
288 fut.set_result(result)
289
290
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700291def _set_concurrent_future_state(concurrent, source):
292 """Copy state from a future to a concurrent.futures.Future."""
293 assert source.done()
294 if source.cancelled():
295 concurrent.cancel()
296 if not concurrent.set_running_or_notify_cancel():
297 return
298 exception = source.exception()
299 if exception is not None:
300 concurrent.set_exception(exception)
301 else:
302 result = source.result()
303 concurrent.set_result(result)
304
305
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500306def _copy_future_state(source, dest):
307 """Internal helper to copy state from another Future.
308
309 The other Future may be a concurrent.futures.Future.
310 """
311 assert source.done()
312 if dest.cancelled():
313 return
314 assert not dest.done()
315 if source.cancelled():
316 dest.cancel()
317 else:
318 exception = source.exception()
319 if exception is not None:
320 dest.set_exception(exception)
321 else:
322 result = source.result()
323 dest.set_result(result)
324
325
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700326def _chain_future(source, destination):
327 """Chain two futures so that when one completes, so does the other.
328
329 The result (or exception) of source will be copied to destination.
330 If destination is cancelled, source gets cancelled too.
331 Compatible with both asyncio.Future and concurrent.futures.Future.
332 """
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700333 if not isfuture(source) and not isinstance(source,
334 concurrent.futures.Future):
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700335 raise TypeError('A future is required for source argument')
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700336 if not isfuture(destination) and not isinstance(destination,
337 concurrent.futures.Future):
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700338 raise TypeError('A future is required for destination argument')
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500339 source_loop = _get_loop(source) if isfuture(source) else None
340 dest_loop = _get_loop(destination) if isfuture(destination) else None
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700341
342 def _set_state(future, other):
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700343 if isfuture(future):
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500344 _copy_future_state(other, future)
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700345 else:
346 _set_concurrent_future_state(future, other)
347
348 def _call_check_cancel(destination):
349 if destination.cancelled():
350 if source_loop is None or source_loop is dest_loop:
351 source.cancel()
352 else:
353 source_loop.call_soon_threadsafe(source.cancel)
354
355 def _call_set_state(source):
356 if dest_loop is None or dest_loop is source_loop:
357 _set_state(destination, source)
358 else:
359 dest_loop.call_soon_threadsafe(_set_state, destination, source)
360
361 destination.add_done_callback(_call_check_cancel)
362 source.add_done_callback(_call_set_state)
363
364
365def wrap_future(future, *, loop=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700366 """Wrap concurrent.futures.Future object."""
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700367 if isfuture(future):
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700368 return future
369 assert isinstance(future, concurrent.futures.Future), \
Yury Selivanov6370f342017-12-10 18:36:12 -0500370 f'concurrent.futures.Future is expected, got {future!r}'
Yury Selivanov7661db62016-05-16 15:38:39 -0400371 if loop is None:
372 loop = events.get_event_loop()
373 new_future = loop.create_future()
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700374 _chain_future(future, new_future)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700375 return new_future
INADA Naokic411a7d2016-10-18 11:48:14 +0900376
377
378try:
379 import _asyncio
380except ImportError:
381 pass
382else:
Yury Selivanov01c521b2016-10-23 22:34:35 -0400383 # _CFuture is needed for tests.
384 Future = _CFuture = _asyncio.Future