base_futures.py 2.0 KB

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