Skip to content

mode.utils.tracebacks

Traceback utilities.

Traceback

Bases: _BaseTraceback

Traceback object with truncated frames.

Source code in mode/utils/tracebacks.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
class Traceback(_BaseTraceback):
    """Traceback object with truncated frames."""

    def __init__(
        self,
        frame: FrameType,
        lineno: Optional[int] = None,
        lasti: Optional[int] = None,
    ) -> None:
        self.tb_frame = frame
        self.tb_lineno = lineno if lineno is not None else frame.f_lineno
        self.tb_lasti = lasti if lasti is not None else frame.f_lasti
        self.tb_next = None

    @classmethod
    def from_task(
        cls, task: asyncio.Task, *, limit: int = DEFAULT_MAX_FRAMES
    ) -> _BaseTraceback:
        coro = task._coro  # type: ignore
        return cls.from_coroutine(coro, limit=limit)

    @classmethod
    def from_agen(
        cls, agen: AsyncGenerator, *, limit: int = DEFAULT_MAX_FRAMES
    ) -> _BaseTraceback:
        return cls.from_coroutine(agen, limit=limit)

    @classmethod
    def from_coroutine(  # noqa: C901
        cls,
        coro: Union[AsyncGenerator, Coroutine, Generator],
        *,
        depth: int = 0,
        limit: Optional[int] = DEFAULT_MAX_FRAMES,
    ) -> _BaseTraceback:
        try:
            frame = cls._detect_frame(coro)
        except AttributeError:
            if type(coro).__name__ == "async_generator_asend":
                return _Truncated(filename="async_generator_asend")
            raise
        if limit is None:
            limit = getattr(sys, "tracebacklimit", None)
        if limit is not None and limit < 0:
            limit = 0
        frames = []
        num_frames = 0
        current_frame = frame
        while current_frame is not None:
            if limit is not None:
                if num_frames > limit:
                    break
            frames.append(current_frame)
            num_frames += 1
            current_frame = current_frame.f_back  # type: ignore
        frames.reverse()
        prev: Optional[_BaseTraceback] = None
        root: Optional[_BaseTraceback] = None
        for f in frames:
            tb = cls(f)
            if root is None:
                root = tb
            if prev is not None:
                prev.tb_next = tb
            prev = tb
        cr_await = cls._get_coroutine_next(coro)
        if cr_await is not None and asyncio.iscoroutine(cr_await):
            next_node: _BaseTraceback
            if limit is not None and depth > limit:
                next_node = _Truncated()
            else:
                next_node = cls.from_coroutine(
                    cr_await, limit=limit, depth=depth + 1
                )
            if root is not None:
                root.tb_next = next_node
            else:
                return next_node
        if root is None:
            raise RuntimeError("cannot find stack of coroutine")
        return root

    @classmethod
    def _detect_frame(cls, obj: Any) -> FrameType:
        if inspect.isasyncgen(obj):
            return cls._get_agen_frame(obj)
        return cls._get_coroutine_frame(obj)

    @classmethod
    def _get_coroutine_frame(
        cls, coro: Union[Coroutine, Generator]
    ) -> FrameType:
        try:
            if inspect.isgenerator(coro):
                # is a @asyncio.coroutine wrapped generator
                return cast(Generator, coro).gi_frame
            else:
                # is an async def function
                return cast(Coroutine, coro).cr_frame
        except AttributeError as exc:
            raise cls._what_is_this(coro) from exc

    @classmethod
    def _what_is_this(cls, obj: Any) -> AttributeError:
        return AttributeError(
            f"WHAT IS THIS? str={obj} repr={obj!r} typ={type(obj)!r} dir={dir(obj)}"
        )

    @classmethod
    def _get_agen_frame(cls, agen: AsyncGenerator) -> FrameType:
        try:
            return agen.ag_frame
        except AttributeError as exc:
            raise cls._what_is_this(agen) from exc

    @staticmethod
    def _get_coroutine_next(
        coro: Union[AsyncGenerator, Coroutine, Generator],
    ) -> Any:
        if inspect.isasyncgen(coro):
            # is a async def async-generator
            return cast(AsyncGenerator, coro).ag_await
        elif inspect.isgenerator(coro):
            # is a @asyncio.coroutine wrapped generator
            return cast(Generator, coro).gi_yieldfrom
        else:
            # is an async def function
            return cast(Coroutine, coro).cr_await

format_coro_stack(coro, *, limit=DEFAULT_MAX_FRAMES, capture_locals=False)

Format coroutine stack trace as a string.

Source code in mode/utils/tracebacks.py
 98
 99
100
101
102
103
104
105
106
107
def format_coro_stack(
    coro: Coroutine,
    *,
    limit: int = DEFAULT_MAX_FRAMES,
    capture_locals: bool = False,
) -> str:
    """Format coroutine stack trace as a string."""
    f = io.StringIO()
    print_coro_stack(coro, file=f, limit=limit, capture_locals=capture_locals)
    return f.getvalue()

format_task_stack(task, *, limit=DEFAULT_MAX_FRAMES, capture_locals=False)

Format asyncio.Task stack trace as a string.

Source code in mode/utils/tracebacks.py
86
87
88
89
90
91
92
93
94
95
def format_task_stack(
    task: asyncio.Task,
    *,
    limit: int = DEFAULT_MAX_FRAMES,
    capture_locals: bool = False,
) -> str:
    """Format `asyncio.Task` stack trace as a string."""
    f = io.StringIO()
    print_task_stack(task, file=f, limit=limit, capture_locals=capture_locals)
    return f.getvalue()

print_agen_stack(agen, *, file=sys.stderr, limit=DEFAULT_MAX_FRAMES, capture_locals=False)

Print the stack trace for a currently running async generator.

Source code in mode/utils/tracebacks.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def print_agen_stack(
    agen: AsyncGenerator,
    *,
    file: IO = sys.stderr,
    limit: int = DEFAULT_MAX_FRAMES,
    capture_locals: bool = False,
) -> None:
    """Print the stack trace for a currently running async generator."""
    print(f"Stack for {agen!r} (most recent call last):", file=file)
    tb = Traceback.from_agen(agen, limit=limit)
    print_list(
        StackSummary.extract(
            cast(Generator, walk_tb(cast(TracebackType, tb))),
            limit=limit,
            capture_locals=capture_locals,
        ),
        file=file,
    )

print_coro_stack(coro, *, file=sys.stderr, limit=DEFAULT_MAX_FRAMES, capture_locals=False)

Print the stack trace for a currently running coroutine.

Source code in mode/utils/tracebacks.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def print_coro_stack(
    coro: Coroutine,
    *,
    file: IO = sys.stderr,
    limit: int = DEFAULT_MAX_FRAMES,
    capture_locals: bool = False,
) -> None:
    """Print the stack trace for a currently running coroutine."""
    print(f"Stack for {coro!r} (most recent call last):", file=file)
    tb = Traceback.from_coroutine(coro, limit=limit)
    print_list(
        StackSummary.extract(
            cast(Generator, walk_tb(cast(TracebackType, tb))),
            limit=limit,
            capture_locals=capture_locals,
        ),
        file=file,
    )

print_task_stack(task, *, file=sys.stderr, limit=DEFAULT_MAX_FRAMES, capture_locals=False)

Print the stack trace for an asyncio.Task.

Source code in mode/utils/tracebacks.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def print_task_stack(
    task: asyncio.Task,
    *,
    file: IO = sys.stderr,
    limit: int = DEFAULT_MAX_FRAMES,
    capture_locals: bool = False,
) -> None:
    """Print the stack trace for an `asyncio.Task`."""
    print(f"Stack for {task!r} (most recent call last):", file=file)
    tb = Traceback.from_task(task, limit=limit)
    print_list(
        StackSummary.extract(
            cast(Generator, walk_tb(cast(TracebackType, tb))),
            limit=limit,
            capture_locals=capture_locals,
        ),
        file=file,
    )