|
| 1 | +import contextvars |
| 2 | +from contextlib import contextmanager |
| 3 | +from typing import Any, Callable, Dict, TypeVar, cast |
| 4 | + |
| 5 | +_context_stack: contextvars.ContextVar[list] = contextvars.ContextVar("posthog_context_stack", default=[{}]) |
| 6 | + |
| 7 | + |
| 8 | +def _get_current_context() -> Dict[str, Any]: |
| 9 | + return _context_stack.get()[-1] |
| 10 | + |
| 11 | + |
| 12 | +@contextmanager |
| 13 | +def new_context(fresh=False): |
| 14 | + """ |
| 15 | + Create a new context scope that will be active for the duration of the with block. |
| 16 | + Any tags set within this scope will be isolated to this context. Any exceptions raised |
| 17 | + or events captured within the context will be tagged with the context tags. |
| 18 | +
|
| 19 | + Args: |
| 20 | + fresh: Whether to start with a fresh context (default: False). |
| 21 | + If False, inherits tags from parent context. |
| 22 | + If True, starts with no tags. |
| 23 | +
|
| 24 | + Examples: |
| 25 | + # Inherit parent context tags |
| 26 | + with posthog.new_context(): |
| 27 | + posthog.tag("request_id", "123") |
| 28 | + # Both this event and the exception will be tagged with the context tags |
| 29 | + posthog.capture("event_name", {"property": "value"}) |
| 30 | + raise ValueError("Something went wrong") |
| 31 | +
|
| 32 | + # Start with fresh context (no inherited tags) |
| 33 | + with posthog.new_context(fresh=True): |
| 34 | + posthog.tag("request_id", "123") |
| 35 | + # Both this event and the exception will be tagged with the context tags |
| 36 | + posthog.capture("event_name", {"property": "value"}) |
| 37 | + raise ValueError("Something went wrong") |
| 38 | +
|
| 39 | + """ |
| 40 | + import posthog |
| 41 | + |
| 42 | + current_tags = _get_current_context().copy() |
| 43 | + current_stack = _context_stack.get() |
| 44 | + new_stack = current_stack + [{}] if fresh else current_stack + [current_tags] |
| 45 | + token = _context_stack.set(new_stack) |
| 46 | + |
| 47 | + try: |
| 48 | + yield |
| 49 | + except Exception as e: |
| 50 | + posthog.capture_exception(e) |
| 51 | + raise |
| 52 | + finally: |
| 53 | + _context_stack.reset(token) |
| 54 | + |
| 55 | + |
| 56 | +def tag(key: str, value: Any) -> None: |
| 57 | + """ |
| 58 | + Add a tag to the current context. |
| 59 | +
|
| 60 | + Args: |
| 61 | + key: The tag key |
| 62 | + value: The tag value |
| 63 | +
|
| 64 | + Example: |
| 65 | + posthog.tag("user_id", "123") |
| 66 | + """ |
| 67 | + _get_current_context()[key] = value |
| 68 | + |
| 69 | + |
| 70 | +def get_tags() -> Dict[str, Any]: |
| 71 | + """ |
| 72 | + Get all tags from the current context. Note, modifying |
| 73 | + the returned dictionary will not affect the current context. |
| 74 | +
|
| 75 | + Returns: |
| 76 | + Dict of all tags in the current context |
| 77 | + """ |
| 78 | + return _get_current_context().copy() |
| 79 | + |
| 80 | + |
| 81 | +def clear_tags() -> None: |
| 82 | + """Clear all tags in the current context.""" |
| 83 | + _get_current_context().clear() |
| 84 | + |
| 85 | + |
| 86 | +F = TypeVar("F", bound=Callable[..., Any]) |
| 87 | + |
| 88 | + |
| 89 | +def scoped(fresh=False): |
| 90 | + """ |
| 91 | + Decorator that creates a new context for the function. Simply wraps |
| 92 | + the function in a with posthog.new_context(): block. |
| 93 | +
|
| 94 | + Args: |
| 95 | + fresh: Whether to start with a fresh context (default: False) |
| 96 | +
|
| 97 | + Example: |
| 98 | + @posthog.scoped() |
| 99 | + def process_payment(payment_id): |
| 100 | + posthog.tag("payment_id", payment_id) |
| 101 | + posthog.tag("payment_method", "credit_card") |
| 102 | +
|
| 103 | + # This event will be captured with tags |
| 104 | + posthog.capture("payment_started") |
| 105 | + # If this raises an exception, it will be captured with tags |
| 106 | + # and then re-raised |
| 107 | + some_risky_function() |
| 108 | + """ |
| 109 | + |
| 110 | + def decorator(func: F) -> F: |
| 111 | + from functools import wraps |
| 112 | + |
| 113 | + @wraps(func) |
| 114 | + def wrapper(*args, **kwargs): |
| 115 | + with new_context(fresh=fresh): |
| 116 | + return func(*args, **kwargs) |
| 117 | + |
| 118 | + return cast(F, wrapper) |
| 119 | + |
| 120 | + return decorator |
0 commit comments