Skip to content

Commit c79c1c1

Browse files
committed
try supporting async too
1 parent fb5f809 commit c79c1c1

File tree

1 file changed

+35
-12
lines changed

1 file changed

+35
-12
lines changed

posthog/scopes.py

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,32 @@
1-
import threading
1+
import sys
22
from contextlib import contextmanager
33
from typing import Any, Callable, Dict, TypeVar, cast
44

5-
_scopes_local = threading.local()
5+
# Use contextvars if available (Python 3.7+), otherwise fall back to threading.local
6+
if sys.version_info >= (3, 7):
7+
import contextvars
8+
_context_stack: contextvars.ContextVar[list] = contextvars.ContextVar(
9+
'posthog_context_stack',
10+
default=[{}]
11+
)
12+
_use_contextvars = True
13+
else:
14+
import threading
15+
_scopes_local = threading.local()
16+
_use_contextvars = False
617

718

819
def _init_guard() -> None:
9-
if not hasattr(_scopes_local, "context_stack"):
20+
if not _use_contextvars and not hasattr(_scopes_local, "context_stack"):
1021
_scopes_local.context_stack = [{}]
1122

1223

1324
def _get_current_context() -> Dict[str, Any]:
14-
_init_guard()
15-
return _scopes_local.context_stack[-1]
25+
if _use_contextvars:
26+
return _context_stack.get()[-1]
27+
else:
28+
_init_guard()
29+
return _scopes_local.context_stack[-1]
1630

1731

1832
@contextmanager
@@ -40,13 +54,22 @@ def new_context():
4054
posthog.capture_exception(e)
4155
raise e
4256
"""
43-
_init_guard()
44-
_scopes_local.context_stack.append({})
45-
try:
46-
yield
47-
finally:
48-
if len(_scopes_local.context_stack) > 1:
49-
_scopes_local.context_stack.pop()
57+
if _use_contextvars:
58+
current_stack = _context_stack.get()
59+
new_stack = current_stack + [{}]
60+
token = _context_stack.set(new_stack)
61+
try:
62+
yield
63+
finally:
64+
_context_stack.reset(token)
65+
else:
66+
_init_guard()
67+
_scopes_local.context_stack.append({})
68+
try:
69+
yield
70+
finally:
71+
if len(_scopes_local.context_stack) > 1:
72+
_scopes_local.context_stack.pop()
5073

5174

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

0 commit comments

Comments
 (0)