_result.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """
  2. Hook wrapper "result" utilities.
  3. """
  4. import sys
  5. def _raise_wrapfail(wrap_controller, msg):
  6. co = wrap_controller.gi_code
  7. raise RuntimeError(
  8. "wrap_controller at %r %s:%d %s"
  9. % (co.co_name, co.co_filename, co.co_firstlineno, msg)
  10. )
  11. class HookCallError(Exception):
  12. """Hook was called wrongly."""
  13. class _Result:
  14. def __init__(self, result, excinfo):
  15. self._result = result
  16. self._excinfo = excinfo
  17. @property
  18. def excinfo(self):
  19. return self._excinfo
  20. @classmethod
  21. def from_call(cls, func):
  22. __tracebackhide__ = True
  23. result = excinfo = None
  24. try:
  25. result = func()
  26. except BaseException:
  27. excinfo = sys.exc_info()
  28. return cls(result, excinfo)
  29. def force_result(self, result):
  30. """Force the result(s) to ``result``.
  31. If the hook was marked as a ``firstresult`` a single value should
  32. be set otherwise set a (modified) list of results. Any exceptions
  33. found during invocation will be deleted.
  34. """
  35. self._result = result
  36. self._excinfo = None
  37. def get_result(self):
  38. """Get the result(s) for this hook call.
  39. If the hook was marked as a ``firstresult`` only a single value
  40. will be returned otherwise a list of results.
  41. """
  42. __tracebackhide__ = True
  43. if self._excinfo is None:
  44. return self._result
  45. else:
  46. ex = self._excinfo
  47. raise ex[1].with_traceback(ex[2])