|
1 | | -import sys |
2 | | -import threading |
| 1 | +import contextvars |
3 | 2 | from contextlib import contextmanager |
4 | 3 | from typing import Any, Callable, Dict, TypeVar, cast |
5 | 4 |
|
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=[{}]) |
21 | 6 |
|
22 | 7 |
|
23 | 8 | 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] |
29 | 10 |
|
30 | 11 |
|
31 | 12 | @contextmanager |
@@ -53,22 +34,13 @@ def new_context(): |
53 | 34 | posthog.capture_exception(e) |
54 | 35 | raise e |
55 | 36 | """ |
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) |
72 | 44 |
|
73 | 45 |
|
74 | 46 | def tag(key: str, value: Any) -> None: |
|
0 commit comments