_init_implementation.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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: "sentry_sdk.Client") -> None:
  15. self._client = client
  16. def __enter__(self) -> "_InitGuard":
  17. warnings.warn(
  18. self._CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE,
  19. stacklevel=2,
  20. category=DeprecationWarning,
  21. )
  22. return self
  23. def __exit__(self, exc_type: "Any", exc_value: "Any", tb: "Any") -> None:
  24. warnings.warn(
  25. self._CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE,
  26. stacklevel=2,
  27. category=DeprecationWarning,
  28. )
  29. c = self._client
  30. if c is not None:
  31. c.close()
  32. def _check_python_deprecations() -> None:
  33. # Since we're likely to deprecate Python versions in the future, I'm keeping
  34. # this handy function around. Use this to detect the Python version used and
  35. # to output logger.warning()s if it's deprecated.
  36. pass
  37. def _init(*args: "Optional[str]", **kwargs: "Any") -> "ContextManager[Any]":
  38. """Initializes the SDK and optionally integrations.
  39. This takes the same arguments as the client constructor.
  40. """
  41. client = sentry_sdk.Client(*args, **kwargs)
  42. sentry_sdk.get_global_scope().set_client(client)
  43. _check_python_deprecations()
  44. rv = _InitGuard(client)
  45. return rv
  46. if TYPE_CHECKING:
  47. # Make mypy, PyCharm and other static analyzers think `init` is a type to
  48. # have nicer autocompletion for params.
  49. #
  50. # Use `ClientConstructor` to define the argument types of `init` and
  51. # `ContextManager[Any]` to tell static analyzers about the return type.
  52. class init(sentry_sdk.consts.ClientConstructor, _InitGuard): # noqa: N801
  53. pass
  54. else:
  55. # Alias `init` for actual usage. Go through the lambda indirection to throw
  56. # PyCharm off of the weakly typed signature (it would otherwise discover
  57. # both the weakly typed signature of `_init` and our faked `init` type).
  58. init = (lambda: _init)()