_init_implementation.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import warnings
  2. from typing import TYPE_CHECKING
  3. import sentry_sdk
  4. if TYPE_CHECKING:
  5. from typing import Any, ContextManager, Optional
  6. import sentry_sdk.consts
  7. class _InitGuard:
  8. _CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE = (
  9. "Using the return value of sentry_sdk.init as a context manager "
  10. "and manually calling the __enter__ and __exit__ methods on the "
  11. "return value are deprecated. We are no longer maintaining this "
  12. "functionality, and we will remove it in the next major release."
  13. )
  14. def __init__(self, client):
  15. # type: (sentry_sdk.Client) -> None
  16. self._client = client
  17. def __enter__(self):
  18. # type: () -> _InitGuard
  19. warnings.warn(
  20. self._CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE,
  21. stacklevel=2,
  22. category=DeprecationWarning,
  23. )
  24. return self
  25. def __exit__(self, exc_type, exc_value, tb):
  26. # type: (Any, Any, Any) -> None
  27. warnings.warn(
  28. self._CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE,
  29. stacklevel=2,
  30. category=DeprecationWarning,
  31. )
  32. c = self._client
  33. if c is not None:
  34. c.close()
  35. def _check_python_deprecations():
  36. # type: () -> None
  37. # Since we're likely to deprecate Python versions in the future, I'm keeping
  38. # this handy function around. Use this to detect the Python version used and
  39. # to output logger.warning()s if it's deprecated.
  40. pass
  41. def _init(*args, **kwargs):
  42. # type: (*Optional[str], **Any) -> ContextManager[Any]
  43. """Initializes the SDK and optionally integrations.
  44. This takes the same arguments as the client constructor.
  45. """
  46. client = sentry_sdk.Client(*args, **kwargs)
  47. sentry_sdk.get_global_scope().set_client(client)
  48. _check_python_deprecations()
  49. rv = _InitGuard(client)
  50. return rv
  51. if TYPE_CHECKING:
  52. # Make mypy, PyCharm and other static analyzers think `init` is a type to
  53. # have nicer autocompletion for params.
  54. #
  55. # Use `ClientConstructor` to define the argument types of `init` and
  56. # `ContextManager[Any]` to tell static analyzers about the return type.
  57. class init(sentry_sdk.consts.ClientConstructor, _InitGuard): # noqa: N801
  58. pass
  59. else:
  60. # Alias `init` for actual usage. Go through the lambda indirection to throw
  61. # PyCharm off of the weakly typed signature (it would otherwise discover
  62. # both the weakly typed signature of `_init` and our faked `init` type).
  63. init = (lambda: _init)()