From d42422674379afd90ac5039e4fbac13281178ff2 Mon Sep 17 00:00:00 2001 From: Daniel Szoke <7881302+szokeasaurusrex@users.noreply.github.com> Date: Tue, 12 Nov 2024 09:16:11 +0100 Subject: [PATCH] ref(init): Deprecate `sentry_sdk.init` context manager (#3729) It is possible to use the return value of `sentry_sdk.init` as a context manager; however, this functionality has not been maintained for a long time, and it does not seem to be documented anywhere. So, we are deprecating this functionality, and we will remove it in the next major release. Closes #3282 --- sentry_sdk/_init_implementation.py | 21 +++++++++++++++++++++ tests/test_api.py | 17 +++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/sentry_sdk/_init_implementation.py b/sentry_sdk/_init_implementation.py index 256a69ee83..eb02b3d11e 100644 --- a/sentry_sdk/_init_implementation.py +++ b/sentry_sdk/_init_implementation.py @@ -1,3 +1,5 @@ +import warnings + from typing import TYPE_CHECKING import sentry_sdk @@ -9,16 +11,35 @@ class _InitGuard: + _CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE = ( + "Using the return value of sentry_sdk.init as a context manager " + "and manually calling the __enter__ and __exit__ methods on the " + "return value are deprecated. We are no longer maintaining this " + "functionality, and we will remove it in the next major release." + ) + def __init__(self, client): # type: (sentry_sdk.Client) -> None self._client = client def __enter__(self): # type: () -> _InitGuard + warnings.warn( + self._CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE, + stacklevel=2, + category=DeprecationWarning, + ) + return self def __exit__(self, exc_type, exc_value, tb): # type: (Any, Any, Any) -> None + warnings.warn( + self._CONTEXT_MANAGER_DEPRECATION_WARNING_MESSAGE, + stacklevel=2, + category=DeprecationWarning, + ) + c = self._client if c is not None: c.close() diff --git a/tests/test_api.py b/tests/test_api.py index ae194af7fd..3b2a9c8fb7 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,6 +1,7 @@ import pytest from unittest import mock +import sentry_sdk from sentry_sdk import ( capture_exception, continue_trace, @@ -195,3 +196,19 @@ def test_push_scope_deprecation(): with pytest.warns(DeprecationWarning): with push_scope(): ... + + +def test_init_context_manager_deprecation(): + with pytest.warns(DeprecationWarning): + with sentry_sdk.init(): + ... + + +def test_init_enter_deprecation(): + with pytest.warns(DeprecationWarning): + sentry_sdk.init().__enter__() + + +def test_init_exit_deprecation(): + with pytest.warns(DeprecationWarning): + sentry_sdk.init().__exit__(None, None, None)