Debian Codegraph @

src/pluggy/_result.py

raw
1 """
2 Hook wrapper "result" utilities.
3 """
4
5 from __future__ import annotations
6
7 from types import TracebackType
8 from typing import Callable
9 from typing import cast
10 from typing import final
11 from typing import Generic
12 from typing import Optional
13 from typing import TypeVar
14
15
16 _ExcInfo = tuple[type[BaseException], BaseException, Optional[TracebackType]]
17 ResultType = TypeVar("ResultType")
18
19
20 class HookCallError(Exception):
21 """Hook was called incorrectly."""
22
23
24 @final
25 class Result(Generic[ResultType]):
26 """An object used to inspect and set the result in a :ref:`hook wrapper
27 <hookwrappers>`."""
28
29 __slots__ = ("_result", "_exception", "_traceback")
30
31 def __init__(
32 self,
33 result: ResultType | None,
34 exception: BaseException | None,
35 ) -> None:
36 """:meta private:"""
37 self._result = result
38 self._exception = exception
39 # Exception __traceback__ is mutable, this keeps the original.
40 self._traceback = exception.__traceback__ if exception is not None else None
41
42 @property
43 def excinfo(self) -> _ExcInfo | None:
44 """:meta private:"""
45 exc = self._exception
46 if exc is None:
47 return None
48 else:
49 return (type(exc), exc, self._traceback)
50
51 @property
52 def exception(self) -> BaseException | None:
53 """:meta private:"""
54 return self._exception
55
56 @classmethod
57 def from_call(cls, func: Callable[[], ResultType]) -> Result[ResultType]:
58 """:meta private:"""
59 __tracebackhide__ = True
60 result = exception = None
61 try:
62 result = func()
63 except BaseException as exc:
64 exception = exc
65 return cls(result, exception)
66
67 def force_result(self, result: ResultType) -> None:
68 """Force the result(s) to ``result``.
69
70 If the hook was marked as a ``firstresult`` a single value should
71 be set, otherwise set a (modified) list of results. Any exceptions
72 found during invocation will be deleted.
73
74 This overrides any previous result or exception.
75 """
76 self._result = result
77 self._exception = None
78 self._traceback = None
79
80 def force_exception(self, exception: BaseException) -> None:
81 """Force the result to fail with ``exception``.
82
83 This overrides any previous result or exception.
84
85 .. versionadded:: 1.1.0
86 """
87 self._result = None
88 self._exception = exception
89 self._traceback = exception.__traceback__ if exception is not None else None
90
91 def get_result(self) -> ResultType:
92 """Get the result(s) for this hook call.
93
94 If the hook was marked as a ``firstresult`` only a single value
95 will be returned, otherwise a list of results.
96 """
97 __tracebackhide__ = True
98 exc = self._exception
99 tb = self._traceback
100 if exc is None:
101 return cast(ResultType, self._result)
102 else:
103 raise exc.with_traceback(tb)
104
105
106 # Historical name (pluggy<=1.2), kept for backward compatibility.
107 _Result = Result