Traceback objects encapsulate and offer higher level access to Traceback entries.
| 321 | |
| 322 | |
| 323 | class Traceback(List[TracebackEntry]): |
| 324 | """Traceback objects encapsulate and offer higher level access to Traceback entries.""" |
| 325 | |
| 326 | def __init__( |
| 327 | self, |
| 328 | tb: Union[TracebackType, Iterable[TracebackEntry]], |
| 329 | excinfo: Optional["ReferenceType[ExceptionInfo[BaseException]]"] = None, |
| 330 | ) -> None: |
| 331 | """Initialize from given python traceback object and ExceptionInfo.""" |
| 332 | self._excinfo = excinfo |
| 333 | if isinstance(tb, TracebackType): |
| 334 | |
| 335 | def f(cur: TracebackType) -> Iterable[TracebackEntry]: |
| 336 | cur_: Optional[TracebackType] = cur |
| 337 | while cur_ is not None: |
| 338 | yield TracebackEntry(cur_, excinfo=excinfo) |
| 339 | cur_ = cur_.tb_next |
| 340 | |
| 341 | super().__init__(f(tb)) |
| 342 | else: |
| 343 | super().__init__(tb) |
| 344 | |
| 345 | def cut( |
| 346 | self, |
| 347 | path: Optional[Union["os.PathLike[str]", str]] = None, |
| 348 | lineno: Optional[int] = None, |
| 349 | firstlineno: Optional[int] = None, |
| 350 | excludepath: Optional["os.PathLike[str]"] = None, |
| 351 | ) -> "Traceback": |
| 352 | """Return a Traceback instance wrapping part of this Traceback. |
| 353 | |
| 354 | By providing any combination of path, lineno and firstlineno, the |
| 355 | first frame to start the to-be-returned traceback is determined. |
| 356 | |
| 357 | This allows cutting the first part of a Traceback instance e.g. |
| 358 | for formatting reasons (removing some uninteresting bits that deal |
| 359 | with handling of the exception/traceback). |
| 360 | """ |
| 361 | path_ = None if path is None else os.fspath(path) |
| 362 | excludepath_ = None if excludepath is None else os.fspath(excludepath) |
| 363 | for x in self: |
| 364 | code = x.frame.code |
| 365 | codepath = code.path |
| 366 | if path is not None and str(codepath) != path_: |
| 367 | continue |
| 368 | if ( |
| 369 | excludepath is not None |
| 370 | and isinstance(codepath, Path) |
| 371 | and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator] |
| 372 | ): |
| 373 | continue |
| 374 | if lineno is not None and x.lineno != lineno: |
| 375 | continue |
| 376 | if firstlineno is not None and x.frame.code.firstlineno != firstlineno: |
| 377 | continue |
| 378 | return Traceback(x._rawentry, self._excinfo) |
| 379 | return self |
| 380 |