您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

56 行
1.7 KiB

  1. from __future__ import annotations
  2. import sys
  3. from contextlib import AbstractContextManager
  4. from types import TracebackType
  5. from typing import TYPE_CHECKING, Optional, Type, cast
  6. if sys.version_info < (3, 11):
  7. from ._exceptions import BaseExceptionGroup
  8. if TYPE_CHECKING:
  9. # requires python 3.9
  10. BaseClass = AbstractContextManager[None]
  11. else:
  12. BaseClass = AbstractContextManager
  13. class suppress(BaseClass):
  14. """Backport of :class:`contextlib.suppress` from Python 3.12.1."""
  15. def __init__(self, *exceptions: type[BaseException]):
  16. self._exceptions = exceptions
  17. def __enter__(self) -> None:
  18. pass
  19. def __exit__(
  20. self,
  21. exctype: Optional[Type[BaseException]],
  22. excinst: Optional[BaseException],
  23. exctb: Optional[TracebackType],
  24. ) -> bool:
  25. # Unlike isinstance and issubclass, CPython exception handling
  26. # currently only looks at the concrete type hierarchy (ignoring
  27. # the instance and subclass checking hooks). While Guido considers
  28. # that a bug rather than a feature, it's a fairly hard one to fix
  29. # due to various internal implementation details. suppress provides
  30. # the simpler issubclass based semantics, rather than trying to
  31. # exactly reproduce the limitations of the CPython interpreter.
  32. #
  33. # See http://bugs.python.org/issue12029 for more details
  34. if exctype is None:
  35. return False
  36. if issubclass(exctype, self._exceptions):
  37. return True
  38. if issubclass(exctype, BaseExceptionGroup):
  39. match, rest = cast(BaseExceptionGroup, excinst).split(self._exceptions)
  40. if rest is None:
  41. return True
  42. raise rest
  43. return False