Context manager to suppress specified exceptions After the exception is suppressed, execution proceeds with the next statement following the with statement. with suppress(FileNotFoundError): os.remove(somefile) # Execution still resumes here if the file was a
| 431 | |
| 432 | |
| 433 | class suppress(AbstractContextManager): |
| 434 | """Context manager to suppress specified exceptions |
| 435 | |
| 436 | After the exception is suppressed, execution proceeds with the next |
| 437 | statement following the with statement. |
| 438 | |
| 439 | with suppress(FileNotFoundError): |
| 440 | os.remove(somefile) |
| 441 | # Execution still resumes here if the file was already removed |
| 442 | """ |
| 443 | |
| 444 | def __init__(self, *exceptions): |
| 445 | self._exceptions = exceptions |
| 446 | |
| 447 | def __enter__(self): |
| 448 | pass |
| 449 | |
| 450 | def __exit__(self, exctype, excinst, exctb): |
| 451 | # Unlike isinstance and issubclass, CPython exception handling |
| 452 | # currently only looks at the concrete type hierarchy (ignoring |
| 453 | # the instance and subclass checking hooks). While Guido considers |
| 454 | # that a bug rather than a feature, it's a fairly hard one to fix |
| 455 | # due to various internal implementation details. suppress provides |
| 456 | # the simpler issubclass based semantics, rather than trying to |
| 457 | # exactly reproduce the limitations of the CPython interpreter. |
| 458 | # |
| 459 | # See http://bugs.python.org/issue12029 for more details |
| 460 | if exctype is None: |
| 461 | return |
| 462 | if issubclass(exctype, self._exceptions): |
| 463 | return True |
| 464 | if issubclass(exctype, BaseExceptionGroup): |
| 465 | match, rest = excinst.split(self._exceptions) |
| 466 | if rest is None: |
| 467 | return True |
| 468 | raise rest |
| 469 | return False |
| 470 | |
| 471 | |
| 472 | def _lookup_special(obj, name, default): |
no outgoing calls
no test coverage detected
searching dependent graphs…