Skip to content

Commit 4340e54

Browse files
fix: Stop unconditionally importing contextvars (#6625)
Use the existing `_get_contextvars()` compatibility helper. The thread-local fallback is still needed for Python 3.6 because `contextvars` was added to the standard library in Python 3.7. The `ImportError` is a regression introduced by 2604409. That commit ported code from a branch where the minimum supported Python version had already been raised to 3.7.
1 parent dafa2bd commit 4340e54

1 file changed

Lines changed: 20 additions & 24 deletions

File tree

sentry_sdk/utils.py

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import base64
2-
import contextvars
32
import copy
43
import json
54
import linecache
@@ -84,29 +83,6 @@
8483

8584
_installed_modules = None
8685

87-
_is_sentry_internal_task = contextvars.ContextVar(
88-
"is_sentry_internal_task", default=False
89-
)
90-
91-
# These exceptions won't set the span status to error if they occur. Use
92-
# register_control_flow_exception to add to this list
93-
_control_flow_exception_classes: "set[type]" = set()
94-
95-
96-
def is_internal_task() -> bool:
97-
return _is_sentry_internal_task.get()
98-
99-
100-
@contextmanager
101-
def mark_sentry_task_internal() -> "Generator[None, None, None]":
102-
"""Context manager to mark a task as Sentry internal."""
103-
token = _is_sentry_internal_task.set(True)
104-
try:
105-
yield
106-
finally:
107-
_is_sentry_internal_task.reset(token)
108-
109-
11086
BASE64_ALPHABET = re.compile(r"^[a-zA-Z0-9/+=]*$")
11187

11288
FALSY_ENV_VALUES = frozenset(("false", "f", "n", "no", "off", "0"))
@@ -1468,6 +1444,26 @@ def _get_contextvars() -> "Tuple[bool, type]":
14681444
Please refer to https://docs.sentry.io/platforms/python/contextvars/ for more information.
14691445
"""
14701446

1447+
_is_sentry_internal_task = ContextVar("is_sentry_internal_task", default=False)
1448+
1449+
# These exceptions won't set the span status to error if they occur. Use
1450+
# register_control_flow_exception to add to this list
1451+
_control_flow_exception_classes: "set[type]" = set()
1452+
1453+
1454+
def is_internal_task() -> bool:
1455+
return _is_sentry_internal_task.get()
1456+
1457+
1458+
@contextmanager
1459+
def mark_sentry_task_internal() -> "Generator[None, None, None]":
1460+
"""Context manager to mark a task as Sentry internal."""
1461+
token = _is_sentry_internal_task.set(True)
1462+
try:
1463+
yield
1464+
finally:
1465+
_is_sentry_internal_task.reset(token)
1466+
14711467

14721468
def qualname_from_function(func: "Callable[..., Any]") -> "Optional[str]":
14731469
"""Return the qualified name of func. Works with regular function, lambda, partial and partialmethod."""

0 commit comments

Comments
 (0)