blob: 98a5308ed0618395599aaa8a39e2a1e4ae969969 [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__ = (
Yury Selivanov6370f342017-12-10 18:36:12 -05004 'Future', 'wrap_future', 'isfuture',
5)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07006
Yury Selivanova0c1ba62016-10-28 12:52:37 -04007import concurrent.futures
Yury Selivanovf23746a2018-01-22 19:11:18 -05008import contextvars
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07009import logging
Victor Stinner4c3c6992013-12-19 22:42:40 +010010import sys
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070011
Yury Selivanova0c1ba62016-10-28 12:52:37 -040012from . import base_futures
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070013from . import events
Andrew Svetlov0baa72f2018-09-11 10:13:04 -070014from . import exceptions
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 -040018isfuture = base_futures.isfuture
19
20
21_PENDING = base_futures._PENDING
22_CANCELLED = base_futures._CANCELLED
23_FINISHED = base_futures._FINISHED
24
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070025
26STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
27
28
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070029class Future:
30 """This class is *almost* compatible with concurrent.futures.Future.
31
32 Differences:
33
Antoine Pitrou22b11282017-11-07 17:03:28 +010034 - This class is not thread-safe.
35
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070036 - result() and exception() do not take a timeout argument and
37 raise an exception when the future isn't done yet.
38
39 - Callbacks registered with add_done_callback() are always called
Antoine Pitrou22b11282017-11-07 17:03:28 +010040 via the event loop's call_soon().
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070041
42 - This class is not compatible with the wait() and as_completed()
43 methods in the concurrent.futures package.
44
45 (In Python 3.4 or later we may be able to unify the implementations.)
46 """
47
48 # Class variables serving as defaults for instance variables.
49 _state = _PENDING
50 _result = None
51 _exception = None
52 _loop = None
Victor Stinnerfe22e092014-12-04 23:00:13 +010053 _source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070054
Guido van Rossum1140a032016-09-09 12:54:54 -070055 # This field is used for a dual purpose:
56 # - Its presence is a marker to declare that a class implements
57 # the Future protocol (i.e. is intended to be duck-type compatible).
58 # The value must also be not-None, to enable a subclass to declare
59 # that it is not compatible by setting this to None.
60 # - It is set by __iter__() below so that Task._step() can tell
Andrew Svetlov88743422017-12-11 17:35:49 +020061 # the difference between
62 # `await Future()` or`yield from Future()` (correct) vs.
Guido van Rossum1140a032016-09-09 12:54:54 -070063 # `yield Future()` (incorrect).
64 _asyncio_future_blocking = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070065
Yury Selivanove0aef4f2017-12-25 16:16:10 -050066 __log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070067
68 def __init__(self, *, loop=None):
69 """Initialize the future.
70
Martin Panterc04fb562016-02-10 05:44:01 +000071 The optional event_loop argument allows explicitly setting the event
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070072 loop object used by the future. If it's not provided, the future uses
73 the default event loop.
74 """
75 if loop is None:
76 self._loop = events.get_event_loop()
77 else:
78 self._loop = loop
79 self._callbacks = []
Victor Stinner80f53aa2014-06-27 13:52:20 +020080 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020081 self._source_traceback = format_helpers.extract_stack(
82 sys._getframe(1))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070083
Yury Selivanova0c1ba62016-10-28 12:52:37 -040084 _repr_info = base_futures._future_repr_info
Victor Stinner313a9802014-07-29 12:58:23 +020085
86 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -050087 return '<{} {}>'.format(self.__class__.__name__,
88 ' '.join(self._repr_info()))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070089
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090090 def __del__(self):
Yury Selivanove0aef4f2017-12-25 16:16:10 -050091 if not self.__log_traceback:
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090092 # set_exception() was not called, or result() or exception()
93 # has consumed the exception
94 return
95 exc = self._exception
96 context = {
Yury Selivanov6370f342017-12-10 18:36:12 -050097 'message':
98 f'{self.__class__.__name__} exception was never retrieved',
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090099 'exception': exc,
100 'future': self,
101 }
102 if self._source_traceback:
103 context['source_traceback'] = self._source_traceback
104 self._loop.call_exception_handler(context)
Victor Stinner4c3c6992013-12-19 22:42:40 +0100105
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500106 @property
107 def _log_traceback(self):
108 return self.__log_traceback
109
110 @_log_traceback.setter
111 def _log_traceback(self, val):
112 if bool(val):
113 raise ValueError('_log_traceback can only be set to False')
114 self.__log_traceback = False
115
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500116 def get_loop(self):
117 """Return the event loop the Future is bound to."""
118 return self._loop
119
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700120 def cancel(self):
121 """Cancel the future and schedule callbacks.
122
123 If the future is already done or cancelled, return False. Otherwise,
124 change the future's state to cancelled, schedule the callbacks and
125 return True.
126 """
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500127 self.__log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700128 if self._state != _PENDING:
129 return False
130 self._state = _CANCELLED
Yury Selivanov22feeb82018-01-24 11:31:01 -0500131 self.__schedule_callbacks()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700132 return True
133
Yury Selivanov22feeb82018-01-24 11:31:01 -0500134 def __schedule_callbacks(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700135 """Internal: Ask the event loop to call all callbacks.
136
137 The callbacks are scheduled to be called as soon as possible. Also
138 clears the callback list.
139 """
140 callbacks = self._callbacks[:]
141 if not callbacks:
142 return
143
144 self._callbacks[:] = []
Yury Selivanovf23746a2018-01-22 19:11:18 -0500145 for callback, ctx in callbacks:
146 self._loop.call_soon(callback, self, context=ctx)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700147
148 def cancelled(self):
149 """Return True if the future was cancelled."""
150 return self._state == _CANCELLED
151
152 # Don't implement running(); see http://bugs.python.org/issue18699
153
154 def done(self):
155 """Return True if the future is done.
156
157 Done means either that a result / exception are available, or that the
158 future was cancelled.
159 """
160 return self._state != _PENDING
161
162 def result(self):
163 """Return the result this future represents.
164
165 If the future has been cancelled, raises CancelledError. If the
166 future's result isn't yet available, raises InvalidStateError. If
167 the future is done and has an exception set, this exception is raised.
168 """
169 if self._state == _CANCELLED:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700170 raise exceptions.CancelledError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700171 if self._state != _FINISHED:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700172 raise exceptions.InvalidStateError('Result is not ready.')
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500173 self.__log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174 if self._exception is not None:
175 raise self._exception
176 return self._result
177
178 def exception(self):
179 """Return the exception that was set on this future.
180
181 The exception (or None if no exception was set) is returned only if
182 the future is done. If the future has been cancelled, raises
183 CancelledError. If the future isn't done yet, raises
184 InvalidStateError.
185 """
186 if self._state == _CANCELLED:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700187 raise exceptions.CancelledError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188 if self._state != _FINISHED:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700189 raise exceptions.InvalidStateError('Exception is not set.')
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500190 self.__log_traceback = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700191 return self._exception
192
Yury Selivanovf23746a2018-01-22 19:11:18 -0500193 def add_done_callback(self, fn, *, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194 """Add a callback to be run when the future becomes done.
195
196 The callback is called with a single argument - the future object. If
197 the future is already done when this is called, the callback is
198 scheduled with call_soon.
199 """
200 if self._state != _PENDING:
Yury Selivanovf23746a2018-01-22 19:11:18 -0500201 self._loop.call_soon(fn, self, context=context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700202 else:
Yury Selivanovf23746a2018-01-22 19:11:18 -0500203 if context is None:
204 context = contextvars.copy_context()
205 self._callbacks.append((fn, context))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700206
207 # New method not in PEP 3148.
208
209 def remove_done_callback(self, fn):
210 """Remove all instances of a callback from the "call when done" list.
211
212 Returns the number of callbacks removed.
213 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500214 filtered_callbacks = [(f, ctx)
215 for (f, ctx) in self._callbacks
216 if f != fn]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700217 removed_count = len(self._callbacks) - len(filtered_callbacks)
218 if removed_count:
219 self._callbacks[:] = filtered_callbacks
220 return removed_count
221
222 # So-called internal methods (note: no set_running_or_notify_cancel()).
223
224 def set_result(self, result):
225 """Mark the future done and set its result.
226
227 If the future is already done when this method is called, raises
228 InvalidStateError.
229 """
230 if self._state != _PENDING:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700231 raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700232 self._result = result
233 self._state = _FINISHED
Yury Selivanov22feeb82018-01-24 11:31:01 -0500234 self.__schedule_callbacks()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700235
236 def set_exception(self, exception):
237 """Mark the future done and set an exception.
238
239 If the future is already done when this method is called, raises
240 InvalidStateError.
241 """
242 if self._state != _PENDING:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700243 raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
Victor Stinner95728982014-01-30 16:01:54 -0800244 if isinstance(exception, type):
245 exception = exception()
Yury Selivanov1bd03072016-03-02 11:03:28 -0500246 if type(exception) is StopIteration:
247 raise TypeError("StopIteration interacts badly with generators "
248 "and cannot be raised into a Future")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700249 self._exception = exception
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700250 self._state = _FINISHED
Yury Selivanov22feeb82018-01-24 11:31:01 -0500251 self.__schedule_callbacks()
Yury Selivanove0aef4f2017-12-25 16:16:10 -0500252 self.__log_traceback = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700253
Yury Selivanov0cf16f92017-12-25 10:48:15 -0500254 def __await__(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700255 if not self.done():
Guido van Rossum1140a032016-09-09 12:54:54 -0700256 self._asyncio_future_blocking = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700257 yield self # This tells Task to wait for completion.
Yury Selivanov0cf16f92017-12-25 10:48:15 -0500258 if not self.done():
259 raise RuntimeError("await wasn't used with future")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700260 return self.result() # May raise too.
261
Yury Selivanov0cf16f92017-12-25 10:48:15 -0500262 __iter__ = __await__ # make compatible with 'yield from'.
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400263
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700264
Yury Selivanov01c521b2016-10-23 22:34:35 -0400265# Needed for testing purposes.
266_PyFuture = Future
267
268
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500269def _get_loop(fut):
270 # Tries to call Future.get_loop() if it's available.
271 # Otherwise fallbacks to using the old '_loop' property.
272 try:
273 get_loop = fut.get_loop
274 except AttributeError:
275 pass
276 else:
277 return get_loop()
278 return fut._loop
279
280
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500281def _set_result_unless_cancelled(fut, result):
282 """Helper setting the result only if the future was not cancelled."""
283 if fut.cancelled():
284 return
285 fut.set_result(result)
286
287
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700288def _convert_future_exc(exc):
289 exc_class = type(exc)
290 if exc_class is concurrent.futures.CancelledError:
291 return exceptions.CancelledError(*exc.args)
292 elif exc_class is concurrent.futures.TimeoutError:
293 return exceptions.TimeoutError(*exc.args)
294 elif exc_class is concurrent.futures.InvalidStateError:
295 return exceptions.InvalidStateError(*exc.args)
296 else:
297 return exc
298
299
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700300def _set_concurrent_future_state(concurrent, source):
301 """Copy state from a future to a concurrent.futures.Future."""
302 assert source.done()
303 if source.cancelled():
304 concurrent.cancel()
305 if not concurrent.set_running_or_notify_cancel():
306 return
307 exception = source.exception()
308 if exception is not None:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700309 concurrent.set_exception(_convert_future_exc(exception))
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700310 else:
311 result = source.result()
312 concurrent.set_result(result)
313
314
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500315def _copy_future_state(source, dest):
316 """Internal helper to copy state from another Future.
317
318 The other Future may be a concurrent.futures.Future.
319 """
320 assert source.done()
321 if dest.cancelled():
322 return
323 assert not dest.done()
324 if source.cancelled():
325 dest.cancel()
326 else:
327 exception = source.exception()
328 if exception is not None:
Andrew Svetlov0baa72f2018-09-11 10:13:04 -0700329 dest.set_exception(_convert_future_exc(exception))
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500330 else:
331 result = source.result()
332 dest.set_result(result)
333
334
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700335def _chain_future(source, destination):
336 """Chain two futures so that when one completes, so does the other.
337
338 The result (or exception) of source will be copied to destination.
339 If destination is cancelled, source gets cancelled too.
340 Compatible with both asyncio.Future and concurrent.futures.Future.
341 """
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700342 if not isfuture(source) and not isinstance(source,
343 concurrent.futures.Future):
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700344 raise TypeError('A future is required for source argument')
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700345 if not isfuture(destination) and not isinstance(destination,
346 concurrent.futures.Future):
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700347 raise TypeError('A future is required for destination argument')
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500348 source_loop = _get_loop(source) if isfuture(source) else None
349 dest_loop = _get_loop(destination) if isfuture(destination) else None
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700350
351 def _set_state(future, other):
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700352 if isfuture(future):
Yury Selivanov5d7e3b62015-11-17 12:19:41 -0500353 _copy_future_state(other, future)
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700354 else:
355 _set_concurrent_future_state(future, other)
356
357 def _call_check_cancel(destination):
358 if destination.cancelled():
359 if source_loop is None or source_loop is dest_loop:
360 source.cancel()
361 else:
362 source_loop.call_soon_threadsafe(source.cancel)
363
364 def _call_set_state(source):
Yury Selivanovfdccfe02018-05-28 17:10:20 -0400365 if (destination.cancelled() and
366 dest_loop is not None and dest_loop.is_closed()):
367 return
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700368 if dest_loop is None or dest_loop is source_loop:
369 _set_state(destination, source)
370 else:
371 dest_loop.call_soon_threadsafe(_set_state, destination, source)
372
373 destination.add_done_callback(_call_check_cancel)
374 source.add_done_callback(_call_set_state)
375
376
377def wrap_future(future, *, loop=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700378 """Wrap concurrent.futures.Future object."""
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700379 if isfuture(future):
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700380 return future
381 assert isinstance(future, concurrent.futures.Future), \
Yury Selivanov6370f342017-12-10 18:36:12 -0500382 f'concurrent.futures.Future is expected, got {future!r}'
Yury Selivanov7661db62016-05-16 15:38:39 -0400383 if loop is None:
384 loop = events.get_event_loop()
385 new_future = loop.create_future()
Guido van Rossum841d9ee2015-10-03 08:31:42 -0700386 _chain_future(future, new_future)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700387 return new_future
INADA Naokic411a7d2016-10-18 11:48:14 +0900388
389
390try:
391 import _asyncio
392except ImportError:
393 pass
394else:
Yury Selivanov01c521b2016-10-23 22:34:35 -0400395 # _CFuture is needed for tests.
396 Future = _CFuture = _asyncio.Future