base_futures.py 2.0 KB

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