Yury Selivanov | a0c1ba6 | 2016-10-28 12:52:37 -0400 | [diff] [blame] | 1 | __all__ = [] |
| 2 | |
| 3 | import concurrent.futures._base |
| 4 | import reprlib |
| 5 | |
| 6 | from . import events |
| 7 | |
| 8 | Error = concurrent.futures._base.Error |
| 9 | CancelledError = concurrent.futures.CancelledError |
| 10 | TimeoutError = concurrent.futures.TimeoutError |
| 11 | |
| 12 | |
| 13 | class InvalidStateError(Error): |
| 14 | """The operation is not allowed in this state.""" |
| 15 | |
| 16 | |
| 17 | # States for Future. |
| 18 | _PENDING = 'PENDING' |
| 19 | _CANCELLED = 'CANCELLED' |
| 20 | _FINISHED = 'FINISHED' |
| 21 | |
| 22 | |
| 23 | def isfuture(obj): |
| 24 | """Check for a Future. |
| 25 | |
| 26 | This returns True when obj is a Future instance or is advertising |
| 27 | itself as duck-type compatible by setting _asyncio_future_blocking. |
| 28 | See comment in Future for more details. |
| 29 | """ |
| 30 | return getattr(obj, '_asyncio_future_blocking', None) is not None |
| 31 | |
| 32 | |
| 33 | def _format_callbacks(cb): |
| 34 | """helper function for Future.__repr__""" |
| 35 | size = len(cb) |
| 36 | if not size: |
| 37 | cb = '' |
| 38 | |
| 39 | def format_cb(callback): |
| 40 | return events._format_callback_source(callback, ()) |
| 41 | |
| 42 | if size == 1: |
| 43 | cb = format_cb(cb[0]) |
| 44 | elif size == 2: |
| 45 | cb = '{}, {}'.format(format_cb(cb[0]), format_cb(cb[1])) |
| 46 | elif size > 2: |
| 47 | cb = '{}, <{} more>, {}'.format(format_cb(cb[0]), |
| 48 | size - 2, |
| 49 | format_cb(cb[-1])) |
| 50 | return 'cb=[%s]' % cb |
| 51 | |
| 52 | |
| 53 | def _future_repr_info(future): |
| 54 | # (Future) -> str |
| 55 | """helper function for Future.__repr__""" |
| 56 | info = [future._state.lower()] |
| 57 | if future._state == _FINISHED: |
| 58 | if future._exception is not None: |
| 59 | info.append('exception={!r}'.format(future._exception)) |
| 60 | else: |
| 61 | # use reprlib to limit the length of the output, especially |
| 62 | # for very long strings |
| 63 | result = reprlib.repr(future._result) |
| 64 | info.append('result={}'.format(result)) |
| 65 | if future._callbacks: |
| 66 | info.append(_format_callbacks(future._callbacks)) |
| 67 | if future._source_traceback: |
| 68 | frame = future._source_traceback[-1] |
| 69 | info.append('created at %s:%s' % (frame[0], frame[1])) |
| 70 | return info |