Skip to content

Commit e811aa8

Browse files
committed
we only support python 3.9+
1 parent 52e1cc6 commit e811aa8

File tree

1 file changed

+10
-38
lines changed

1 file changed

+10
-38
lines changed

posthog/scopes.py

Lines changed: 10 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,12 @@
1-
import sys
2-
import threading
1+
import contextvars
32
from contextlib import contextmanager
43
from typing import Any, Callable, Dict, TypeVar, cast
54

6-
# Use contextvars if available (Python 3.7+), otherwise fall back to threading.local
7-
if sys.version_info >= (3, 7):
8-
import contextvars
9-
10-
_context_stack: contextvars.ContextVar[list] = contextvars.ContextVar("posthog_context_stack", default=[{}])
11-
_use_contextvars = True
12-
else:
13-
_use_contextvars = False
14-
15-
_scopes_local = threading.local()
16-
17-
18-
def _init_guard() -> None:
19-
if not _use_contextvars and not hasattr(_scopes_local, "context_stack"):
20-
_scopes_local.context_stack = [{}]
5+
_context_stack: contextvars.ContextVar[list] = contextvars.ContextVar("posthog_context_stack", default=[{}])
216

227

238
def _get_current_context() -> Dict[str, Any]:
24-
if _use_contextvars:
25-
return _context_stack.get()[-1]
26-
else:
27-
_init_guard()
28-
return _scopes_local.context_stack[-1]
9+
return _context_stack.get()[-1]
2910

3011

3112
@contextmanager
@@ -53,22 +34,13 @@ def new_context():
5334
posthog.capture_exception(e)
5435
raise e
5536
"""
56-
if _use_contextvars:
57-
current_stack = _context_stack.get()
58-
new_stack = current_stack + [{}]
59-
token = _context_stack.set(new_stack)
60-
try:
61-
yield
62-
finally:
63-
_context_stack.reset(token)
64-
else:
65-
_init_guard()
66-
_scopes_local.context_stack.append({})
67-
try:
68-
yield
69-
finally:
70-
if len(_scopes_local.context_stack) > 1:
71-
_scopes_local.context_stack.pop()
37+
current_stack = _context_stack.get()
38+
new_stack = current_stack + [{}]
39+
token = _context_stack.set(new_stack)
40+
try:
41+
yield
42+
finally:
43+
_context_stack.reset(token)
7244

7345

7446
def tag(key: str, value: Any) -> None:

0 commit comments

Comments
 (0)